为什么子进程不会在此代码中执行?

Why the child process won't execute in this code?

子进程被跳过,我知道为什么...我使用了调试器但它没有提供任何线索为什么...只有 运行s 通过以父进程的 printf 结尾的代码。 .. 提前致谢。不知道该多说什么我第一次问问题,它问我详细...但我不知道还能说什么,代码的目的是 运行 "verificador" 程序,它是一个验证给定字符串中存在多少禁用词的程序,所以我试过这个,我的 "server" 将通过管道与 "verificador" 通信,然后保存数量"client".

的禁忌词
#include <sys/errno.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

void myabort(const char * msg, int exit_status){
    perror(msg);
    exit(exit_status);
}

int main(int argc,char *argv[])
{
    pid_t pid;
    int fd[2],newfd,nbytes;
    int status;
    char word[]="filipe";
    FILE* f;

    if(pipe(fd)<0) myabort("unable to create unamed pipe",-1);

    switch(pid=fork()){
        case -1: // Error
                myabort("Unable to fork()",-3);
                break;

        case  0:
            printf("CHILD PROCESS");
            if(close(fd[0])==-1) myabort ("CHILD: Error while closing the read end of the pipe.",-4);
            if(close(STDOUT_FILENO)==-1) myabort ("CHILD: Error while closing the standard output.",-4);
            if(dup(fd[1])==-1) myabort("CHILD: Error while duplicating the pipe write end",-5);
            if(close(fd[1])==-1) myabort ("CHILD: Error while closing the original write end descriptor of the pipe.",-4);
            //fprintf(stdout, "%s", word);
            write(1,word,sizeof(word));
            break;

        default:
            printf("PARENT PROCESS");
            wait(&status);
            close(STDIN_FILENO);
            newfd = dup(fd[0]);
            close(fd[0]);
            close(fd[1]);

            f = fdopen(newfd, "r");
            if(f == NULL) myabort("Error opening new file descriptor.", -1);

            execl("verificador", "verificador", "palavras_proibidas", NULL);

            break;
    }
}

确实如此 运行。这是缓冲流的问题。他们可能需要冲洗。

一种解决方案是添加换行符:

printf("CHILD PROCESS\n");

添加换行符在大多数情况下都有效,因为许多终端在遇到换行符时会自动刷新。但是你也可以更具体一点:

printf("CHILD PROCESS");
fflush(stdout);

问题如下:

在这里,您将一个字符串写入标准输出流:

printf("CHILD PROCESS");

由于标准输出是终端时的行缓冲,此输出被缓冲。 通常,这个缓冲区在程序结束时被隐式刷新,显示输出。但是在这里:

if(close(STDOUT_FILENO)==-1) myabort ("CHILD: Error while closing the standard output.",-4);
if(dup(fd[1])==-1) myabort("CHILD: Error while duplicating the pipe write end",-5);

关闭 连接到您的终端的标准输出文件描述符 (1),并将其连接到您的管道。因此,当 stdout-stream 在此之后(隐式或显式)刷新时,输出将进入管道!

您必须确保在关闭文件描述符之前刷新输出,不仅要确保它被打印到终端,而且不要破坏通过管道与您的验证器进程的通信.因为,就目前而言,您的验证器进程将收到字符串

"filipe[=12=]CHILD PROCESS"

当您的子进程结束时标准输出流被隐式刷新(即 returns 来自 main()

解决这种情况的最简单和最安全的方法是调用

fflush(stdout);

在您关闭文件描述符 1 之前。