1

每次写入特定的 FIFO 时,我都在编写一些代码来创建一个新文件夹:

int main (int argc, char* argv[]) {
if (argc != 2) {
    printf("Usage: %s <directory>\n",argv[0]);
    exit(0);
}
int ret = chdir(argv[1]);
if (ret < 0) {
    printf("Could not chdir to %s\n",argv[1]);
    perror("");
    exit(0);
}

ret = mkfifo("create",0666);
if (ret < 0) {
    perror("Could not make create fifo");
    return 0;
}
int ctfd = open("create",O_RDWR);
if (ctfd < 0) {
    perror("Could not open create");
    return 0;
}
char create[1];
//socket counter
int count = 0;
char crdir[15];

for(;;ret = read(ctfd,create,1)) {
    //printf("%s %d\n",create,count);
    if (ret < 0) {
        perror("Failed to read from create");
        continue;
    }
    else if (ret < 1 || create[0] == '\n') {
        continue;
    }

    sprintf(crdir,"%d",count);
    ret = mkdir(crdir,0777);
    if (ret < 0) {
        printf("Failed to create dir");
        perror("");
        continue;
    }
    count++;
    switch(fork()) {
        case -1:
            perror("Failed to fork");
            break;
        case 0:
            printf("%d\n",count);
            break;
        default:
            //char* argv[ ] = {"netclient",cte};
            exit(0);
    }
    printf("test");
}
//execvp()
return 0;

}

但是,当运行时会发生这种情况:

arthur@dent:~/coding/netdir$ mkdir test
arthur@dent:~/coding/netdir$ ./netserver test &
[1] 2122
arthur@dent:~/coding/netdir$ echo 1 > test/create 
[1]+  Done                    ./netserver test
1

我做错了什么?为什么它不继续循环并等待更多输入?FIFO是为读写而打开的,这样写停止时它就不会关闭,是不是不能正常工作?

4

1 回答 1

2

再看一遍,我会说你的问题出在switch( fork() ). fork()子进程返回0子进程,父进程返回子进程的 PID,但你有exit(0);default:所以你退出父进程。

另一个问题(首先看到):您的循环是:

for(;;ret = read(ctfd,create,1)) {
   do_something;
}

这等于:

while( 1 ) {
    do_something;
    ret = read(ctfd,create,1);
}

你在阅读之前“做某事”吗?这会导致未定义的行为,例如因为未定义的内容create

于 2015-02-18T17:58:40.553 回答