C程序示例,演示fork()和pipe()函数

c程序示例,演示fork()和pipe()函数

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

第一让回顾一下fork()和pipe()

fork() – 它创建一个子进程,这个子进程有一个新的PID和PPID。

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

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

输入

Learn programmingPredefined string: at tutorialspoint

登录后复制

输出

Learn programming at tutorialspoint

登录后复制

Explanation

的中文翻译为:

解释

P1 take input of string “learn programming”

登录后复制

使用管道将其发送到 P2。

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

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

返回值

返回值 = 0,子进程。

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

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

演示 fork() 和 pipeline() 的 C 程序

示例

#include#include#include#include#include#includeint main(){   int p12[2];   int p21[2];   char fixed_str[] = " at tutorialspoint";   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  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

", 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

输出

Concatenated string Learn at tutorialspoint

登录后复制

以上就是C程序示例,演示fork()和pipe()函数的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2580822.html

(0)
上一篇 2025年3月6日 13:50:36
下一篇 2025年3月6日 13:50:41

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论