系统编程 - kill,alarm,read,write

1、父进程杀死子进程

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <signal.h>
#include <unistd.h>

int main()
{
	pid_t pid;
	pid = fork();
	if(pid < 0)
	{
		perror("fork failed");
	}
	else if(pid == 0)
	{
		int i =0;
		for(i = 0; i < 5; i++)
		{
			printf("in child process\n");
			sleep(1);
		}
	}
	else
	{
		printf("in father process\n");
		sleep(2);
		printf("kill child process now\n");
		int nRet = kill(pid, SIGINT);
		printf("nRet = %d\n", nRet);
	}
	return 0;
}

2、定时自杀

#include <stdio.h>
#include <unistd.h>

int main()
{
	int sec = 0;
	sec = alarm(5);
	printf("sec = %d\n", sec);
	sleep(1);
	sec = alarm(5);
	printf("sec = %d\n", sec);
	while(1);
	return 0;
}

3、自己实现文件的拷贝cp

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

int main(int argc, char *argv[])
{
	int fd_src, fd_dest;
	char rdBuf[1024] = { 0 };
	int nRet;
	if( argc < 3 )
	{
		printf("parameter num error");
		return 0;
	}

	fd_src = open(argv[1], O_RDONLY);
	if( fd_src < 0 )
	{
		perror("open src");
		return 0;
	}
	fd_dest = open(argv[2], O_WRONLY|O_CREAT, 0666);
	if( fd_dest < 0 )
	{
		perror("open dest");
		return 0;
	}

	while(1)
	{
		nRet = read(fd_src, rdBuf, 1024);
		if( nRet <= 0)
		{
			break;
		}
		write(fd_dest, rdBuf, nRet);
	}
	close(fd_src);
	close(fd_dest);
	return 0;
}

相关推荐

  1. 系统编程和网络编程

    2024-06-14 19:56:02       21 阅读
  2. Linux系统编程_文件编程

    2024-06-14 19:56:02       11 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-14 19:56:02       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-14 19:56:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-14 19:56:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-14 19:56:02       18 阅读

热门阅读

  1. 学习笔记——交通安全分析04

    2024-06-14 19:56:02       7 阅读
  2. 在Android Studio中将某个文件移出Git版本管理

    2024-06-14 19:56:02       7 阅读
  3. 好用的国内镜像源

    2024-06-14 19:56:02       3 阅读
  4. 力扣刷题总结 -- 数组26

    2024-06-14 19:56:02       7 阅读
  5. Linux之history历史指令查看

    2024-06-14 19:56:02       6 阅读
  6. Leetcode:合并两个有序链表

    2024-06-14 19:56:02       7 阅读
  7. ubuntu20.04 minio 安装为服务

    2024-06-14 19:56:02       6 阅读
  8. 查看ubuntu中的分区是什么类型的

    2024-06-14 19:56:02       5 阅读
  9. 矩阵的运算:加减乘除与转置#matlab

    2024-06-14 19:56:02       4 阅读
  10. 数仓SQL如何做code review?

    2024-06-14 19:56:02       6 阅读
  11. 基于大模型的Code Review

    2024-06-14 19:56:02       10 阅读
  12. 力扣第197题:上升的温度

    2024-06-14 19:56:02       6 阅读