Linux系统编程——进程控制函数fork

创建一个新的进程

pid_t fork(void);

返回值

  • 失败-1
  • 成功,两次返回
    • 父进程返回 子进程的id
    • 子进程返回0

获得pid,进程id,获得当前进程

pid_t getpid(void);

获得当前进程父进程的id

pid_t getppid(void);

注意——返回值

特别要注意是的返回值

RETURN VALUE
       On success, the PID of the child process is returned in the parent, and 0  is  returned
       in  the  child.  On failure, -1 is returned in the parent, no child process is created,
       and errno is set appropriately.
  • 成功,两次返回
    • 父进程返回 子进程的id
    • 子进程返回0

例子

//使用pipe完成ps aux | grep bash操作
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>

int main()
{
    
    
	//创建管道
	//int pipe(int pipefd[2]);
	int fd[2];
	int ret = pipe(fd);
	if(ret<0)
	{
    
    
		perror("pipe error");
		return -1;
	}

	//创建子进程
	pid_t pid = fork();
	if(pid<0) 
	{
    
    
		perror("fork error");
		return -1;
	}
	else if(pid>0)
	{
    
    
		//父进程 - 关闭读端
		close(fd[0]);

		//将标准输出重定向到管道的写端
		dup2(fd[1], STDOUT_FILENO);
		
		execlp("ps", "ps", "aux", NULL);

		perror("execlp error");
	}
	else 
	{
    
    
		//子进程 - 关闭写端
		close(fd[1]);
	
		//将标准输入重定向到管道的读端
		dup2(fd[0], STDIN_FILENO);

		execlp("grep", "grep", "--color=auto", "bash", NULL);

		perror("execlp error");
	}

	return 0;
}
// 父进程:
// 1 创建管道
// 2 创建子进程fork
// 3 在父进程中关闭读端fd[0]
// 4 在子进程中关闭写端fd[1]
// 5 在父进程中将标准输出重定向到管道的写端
// 6 在子进程中将标准输入重写向到管道的读端
// 7 在父进程中调用execl函数执行ps aux命令
// 8 在子进程中调用execl函数执行grep bash命令
// 9 在父进程中回收子进程wait函数









猜你喜欢

转载自blog.csdn.net/e891377/article/details/107787044