我正在编写一个程序,在该程序中我使用系统调用 fork() 创建一个子进程,然后创建一个孙子进程,以及在子进程和孙子进程之间创建一个管道。我认为我的实现相当不错,但是当我运行程序时,它只是直接跳过了我代码中的提示。
基本上我们有这个:
-Process 启动
Fork() create child
Child 创建管道
Fork() 创建孙子,管道继承。
TL;DR- 代码跳过 UI 提示,不确定我是否正确输入数据,不确定我是否正确将数据读入进程。
如何读取管道中的输入?
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
void main(int argc, char *argv[])
{
int p[2];
int pid, pid2;
pid = fork();
if(pid == 0)
{
pipe(p);
pid2 = fork();
switch(pid2)
{
case -1:
printf("CASE 1");
exit(-1);
case 0:
close(0);
dup(p[0]);
close(p[0]);
close(p[1]);
execl("./Sort/sort", 0);
break;
default:
close(1);
dup(p[1]);
close(p[1]);
close(p[0]);
execl("./Pre/pre", 0);
break;
}
}
else
{
wait(pid);
printf("Process Completed\n");
exit(0);
}
}
pre 的子进程:
#include <stdio.h>
void main (int argc, char *argv[])
{
char n1[20];
int g1;
FILE *ofp, *ifp;
int track;
ofp = fopen("output.txt", "w");
while(track != -1)
{
printf("Please enter the student's grade and then name, ");
printf("separated by a space: ");
scanf("%3d %s", &g1, n1);
if (g1 >= 60)
{
fprintf(ofp, "%s\n", n1);
}
printf("Add another name?(-1 to quit, 0 to continue): ");
scanf("%d", &track);
}
fclose(ofp);
ifp = fopen("output.txt", "r");
printf("Students that made a 60+:\n");
while(fscanf(ifp, "%s", n1) == 1)
printf("%s\n", n1);
fclose(ifp);
排序的子进程:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int stringcmp(const void *a, const void *b)
{
const char **ia = (const char **)a;
const char **ib = (const char **)b;
return strcmp(*ia, *ib);
}
void main(int argc, char *argv[])
{
int i = 0;
int num = 0;
int j = 0;
char name[20];
printf("How many names would you like to enter? ");
scanf("%d", &num);
char **input = malloc(num * sizeof(char*));
for (i=0; i < num; i++)
{
printf("Please input a name(first only): ");
scanf("%s", name);
input[i] = strdup(name);
}
qsort(input, num, sizeof(char *), stringcmp);
printf("Names:\n");
for(j = 0; j < num; j++)
printf("%s\n", input[j]);
for( i = 0; i < num; i++ ) free(input[i]);
free(input);