为什么这个带有pipe()的C代码突然停止?

  • 本文关键字:代码 突然 pipe c
  • 更新时间 :
  • 英文 :


我是一名计算机科学专业的学生,我附近有这个"操作系统"考试,当我根据老师以前的考试轨道做一些练习时,我发现自己被困在这个

考试上。曲目总结:

编写一个带有两个输入文件(input.txt和out.txt(的C程序,该程序必须创建2个子进程,第一个将从输入文件中读取字符.txt一次读取两个,并且只有在字母相等的情况下才会将它们传递给子n * 2! 然后将继续将它们打印到输出.txt。

我还没有做平等的部分,因为我在崩溃时首先被困在这个上面。 我已经做了几次尝试,但它们总是在 V:55 的第一个序列之后"冻结",我不明白为什么 cicle 是错误的(?...

这是我的尝试:

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <string.h>
#include <limits.h>
#include <pthread.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdbool.h>
#include <signal.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
#define MAX 128
#define argDef 3
int checkArgc(int argc);
int main(int argc, char **argv) {
int pipe1[2], pipe2[2], nbytes, filedesc, pid1, pid2;
char duelettere[2];
char soluzione[MAX];
if (!checkArgc(argc)) {
printf("Numero di file insufficente!an");
exit(1);
}
printf("Qui tutto benen");
/* Apertura file di input.txt */
if ((filedesc = open(argv[1], O_RDONLY)) < 0) {
perror("Errore durante l'apertura dei file.txt an");
exit(1);
}
printf("filedesc : %dn", filedesc);
if (pipe(pipe1) < 0) {
perror("Errore durante la creazione della prima PIPE! an");
exit(1);
}
printf("pipe1 : %pn", pipe1);
if (pipe(pipe2) < 0) {
perror("Errore durante la creazione della seconda PIPE! an");
exit(1);
}
printf("pipe2 : %pn", pipe2);
if ((pid1 = fork() < 0)) {
perror("Errore creazione primo processo figlio an");
exit(1);
}
if (pid1 == 0) { /* Primo figlio */
printf("pid1 : %dn", pid1);
close(pipe1[0]); /* Chiusura canale in entrata, per poter scrivere */
while ((nbytes=read(filedesc, duelettere, 2)) == 2) {
write(pipe1[1], duelettere, 2);
}
close(pipe1[1]); /* Chiudiamo la PIPE che stava scrivendo */
close(filedesc);
} else { /* Siamo nel processo padre, e lanceremo il figlio n^2 */
close(pipe1[1]);
}
if (pid2 = fork() < 0) {
perror("Errore creazione secondo figlioan");
exit(1);
}
if (pid2 == 0) {
printf("pid2 : %d", pid2);
close(pipe1[1]);
close(pipe2[0]);
nbytes = read(pipe1[0], soluzione, strlen(soluzione));
nbytes = write("out.txt", soluzione, strlen(soluzione));
} else { /* Codice del padre */
close(pipe2[1]);
/* Codice finale del padre */
printf("Siamo arrivati nel padrino parte secondan");
}
waitpid(pid1, NULL, 0);
waitpid(pid2, NULL, 0);
return 0;
}
int checkArgc(int argc) {
if (argc != argDef) {
return 0;
} else {
return 1;
}
}

我很抱歉, 有些变量上面有意大利名字,因为我是意大利人。

可能还有其他问题,但这两行肯定是不正确的:

if ((pid1 = fork() < 0))
...
if (pid2 = fork() < 0) {

您应该将它们更改为:

if ((pid1 = fork()) < 0)
...
if ((pid2 = fork()) < 0) {

最新更新