在本题中,我们将演示fork()和pipe()。在这里,我们将为 Linux 创建一个 C 程序,该程序将连接两个字符串,使用 2 个进程,其中一个进程将获取输入并将其发送给其他进程,其他进程将字符串与预定义的字符串连接起来并返回连接后的字符串。
第一让回顾一下fork()和pipe()
fork() - 它创建一个子进程,这个子进程有一个新的PID和PPID。
pipe()是一个Unix、Linux系统调用,用于进程间通信。
让我们举个例子来理解问题,
输入
Learn programming
Predefined string: at tutorialspoint
输出
Learn programming at tutorialspoint
Explanation
的中文翻译为:解释
P1 take input of string “learn programming”
使用管道将其发送到 P2。
P2 连接字符串并将其发送回 p1,p1 将其打印出来。
在程序中,我们将创建两个进程,例如 P1和 P2 使用 fork() 函数。它有以下三个返回值,显示程序的状态。
返回值 < 0,进程创建失败。
返回值 = 0,子进程。
返回值 > 0,这将是子进程到父进程的进程 ID,即父进程将被执行。
我们将创建两个管道,一个用于从 P1 到 P2 进行通信,另一种是从 P2 到 P1,因为管道是一种方式。
演示 fork() 和 pipeline() 的 C 程序
示例
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<string.h>
#include<sys/wait.h>
int 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){
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</p><p>", 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<strlen(fixed_str); 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 tutorialspoint