linux中fork和pipe区别,演示fork()和pipe()的C程序

在此问题中,我们将演示fork()和pipe()。在这里,我们将为Linux创建一个C程序,该程序将连接两个字符串,使用2个进程,其中一个将接受输入并将其发送给其他进程,这些进程将字符串与预定义的字符串连接起来并返回连接的字符串。

首先让概括fork()和pipe()

fork() -它创建一个子进程,该子进程具有新的PID和PPID。

pipe()是Unix,Linux系统调用,用于进程间通信。

让我们以一个例子来理解问题,

输入值Learn programming

Predefined string: at nhooo

输出结果Learn programming at nhooo

说明P1 take input of string “learn programming”

使用管道将其发送到P2。

P2连接字符串并将其发送回给p1打印。

在程序中,我们将使用该fork()函数创建两个进程,分别为P1和P2 。它具有以下三个返回值,它们显示程序的状态。

返回值<0,进程创建失败。

返回值= 0,子进程。

返回值> 0,这将是父进程的子进程的进程ID,即将执行父进程。

我们将创建两个管道,一个管道用于从P1到P2进行通信,另一个管道用于从P2到P1进行通信,因为管道是一种方式。

C程序演示fork()和pipe()

示例#include

#include

#include

#include

#include

#include

int main(){

int p12[2];

int p21[2];

char fixed_str[] = " at nhooo";

char input_str[100];

pid_t P;

if (pipe(p12)==-1 || pipe(p21)==-1 ){

fprintf(stderr, "Filed to create pipe" );

return 1;

}

scanf("%s", input_str);

P = fork();

if (P 

fprintf(stderr, "fork Failed" );

return 1;

}

else if (P > 0){

char concat_str[100];

close(p12[0]);

write(p12[1], input_str, strlen(input_str)+1);

close(p12[1]);

wait(NULL);

close(p21[1]);

read(p21[0], concat_str, 100);

printf("Concatenated string %s\n", concat_str);

close(p21[0]);

}

else{

close(p12[1]);

char concat_str[100];

read(p12[0], concat_str, 100);

int k = strlen(concat_str);

int i;

for (i=0; i

concat_str[k++] = fixed_str[i];

concat_str[k] = '\0';

close(p12[0]);

close(p21[0]);

write(p21[1], concat_str, strlen(concat_str)+1);

close(p21[1]);

exit(0);

}

}

输出结果Concatenated string Learn at nhooo

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值