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

本文详细介绍了如何使用 fork() 函数创建新进程,包括其返回值解析、返回结果及在psaux|grep bash操作中的应用实例。特别强调了返回值的处理,如成功时父进程和子进程的PID区别以及错误处理。
摘要由CSDN通过智能技术生成

创建一个新的进程

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函数









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值