#include <stdio.h>#include <unistd.h>int main(int argc,char **argv){ int fd[2]; pipe(fd); pID_t pID = fork(); if (pID == 0) { close(fd[0]); dup2(fd[1],1); printf("A string"); _exit(0); } close(fd[1]); char text[1000]; size_t size; int p = 0; while ((size = read(fd[0],text+p,1)) == 1) { p++; } close(fd[0]); text[p] = 'exit()
'; printf("%s",text); return 0;}
代码实际上不起作用.正如@kaylum在评论中正确建议的那样,在子进程中调用exit而不是_exit会使代码正常工作.
解决方法 exit()将所有打开的流作为其终止的一部分刷新,而_exit()不刷新 – 因此在调用_exit()时,任何缓冲的输出都会丢失.你可以让它“工作”:
1)通过调用fflush(stdout);在调用_exit()或之前刷新缓冲的输出
2)使用setbuf(stdout,0)禁用stdout的缓冲;在main()的开头.
POSIX要求流被_exit()
刷新:
The exit() function shall then flush all open streams with unwritten
buffered data and close all open streams. Finally,the process shall
be terminated [CX] with the same consequences as described in
Consequences of Process Termination.
同样,要求在之前不刷新流:
总结The _Exit() [CX] and _exit() functions shall not call functions registered with atexit() nor any registered signal handlers. [CX] Open streams shall not be flushed. Whether open streams are closed (without flushing) is implementation-defined. Finally,the calling process shall be terminated with the consequences described below.
以上是内存溢出为你收集整理的为什么这个简单的代码使用`exit`而不能使用`_exit`?全部内容,希望文章能够帮你解决为什么这个简单的代码使用`exit`而不能使用`_exit`?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)