等待来自文件描述符的输入
我正在子进程中重定向 stdin 和 stdout 的文件描述符,如下所示。 现在我希望子进程等待,直到输入描述符上的数据可用。目前,如果数据在输入描述符处不可用,则子进程会采用一些随机值(我猜是 EOF )并终止。
fd0=open("in1.dat", O_RDWR|O_CREAT);
fd1=open("out1.dat", O_RDWR|O_CREAT);
if(pid==0)
{
dup2(fd0, 0); // redirect input to the file
dup2(fd1, 1); // redirect output to the file
execlp("./flip","flip","new","4",NULL);
}
I am redirecting the file descriptors for stdin and stdout in the child process as follows.
Now i want the child process to wait until the data is available at the input descriptor. Currently if data is not available at the input descriptor then the child process takes some random value ( i guess EOF ) and terminates.
fd0=open("in1.dat", O_RDWR|O_CREAT);
fd1=open("out1.dat", O_RDWR|O_CREAT);
if(pid==0)
{
dup2(fd0, 0); // redirect input to the file
dup2(fd1, 1); // redirect output to the file
execlp("./flip","flip","new","4",NULL);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从文件描述符读取将阻塞,直到数据可用为止(除非您将读取安排为非阻塞)。在你的情况下,如果文件是空的,那么读取确实会返回 0 来指示文件结束,并且不会向缓冲区写入任何内容(因此你看到的随机值是你调用 read 之前存在的值)。如果您希望将输入文件视为管道(例如,您希望子进程等待其他人将数据写入文件),那么您希望将输入文件设置为 fifo 而不是常规文件。 (例如,使用 mknod 而不是 open。)
Reading from a file descriptor will block until data is available (unless you arrange for the read to be non-blocking). In your case, if the file is empty, then a read will indeed return 0 to indicate end of file and write nothing into the buffer (so the random value you are seeing there is whatever was there before you called read). If you are wanting to treat the input file as a pipe (eg, you want the child to wait until someone else writes data to the file) then you want to make the input file a fifo rather than a regular file. (eg, use mknod instead of open.)