我有个奇怪的问题。我目前正在创建两个程序,一个将在后台执行,另一个将读取其输出,还允许向另一个运行在后台的程序输入。
问题是,当我将dup2(in, STDIN_FILENO)
行放在后台执行的程序停止打印到文件。
读者:
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
int main()
{
int out, err, in;
size_t i = 0, j = 0;
int offErr = 0, offOut = 0;
char bufErr[1024];
char bufOut[1024];
char *cFifo = "/tmp/out";
char *cFifoErr = "/tmp/err";
char *cFifoIn = "/tmp/in";
out = open(cFifo, O_RDONLY|O_CREAT, 0600);
err = open(cFifoErr, O_RDONLY|O_CREAT, 0600);
in = open(cFifoIn, O_WRONLY|O_CREAT, 0600);
while(1)
{
memset(bufOut, 0, 1024);
memset(bufErr, 0, 1024);
i=0;
j=0;
while(!i && !j)
{
j = pread(err, bufErr, 1024, offErr);
i = pread(out, bufOut, 1024, offOut);
offOut +=i;
offErr +=j;
}
if(i)
write(STDOUT_FILENO, bufOut, 1024);
if(j)
write(STDOUT_FILENO, bufErr, 1024);
}
return 0;
}
作者(背景):
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
int main()
{
int out, in, err;
char *cFifo = "/tmp/out";
char *cInFifo = "/tmp/in";
char *cErrFifo = "/tmp/err";
out = open(cFifo, O_RDWR|O_CREAT|O_TRUNC, 0600);
in = open("/tmp/in", O_RDWR|O_CREAT|O_TRUNC, 0600);
err = open(cErrFifo, O_RDWR|O_CREAT|O_TRUNC, 0600);
dup2(out, STDOUT_FILENO);
dup2(err, STDERR_FILENO);
//dup2(in, STDIN_FILENO); //if I uncomment this it stops printing to out or err
system("python");
while(1);
return 0;
}
最佳答案
取消注释时:
//dup2(in, STDIN_FILENO); //if I uncomment this it stops printing to out or err
您正在从一个空文件中读取Python(它是在打开时创建和/或截断的),因此Python无事可做,退出。
然后,您的读卡器代码就位于
while (1) ;
循环中,不做任何有用的事情。至少,在
printf()
语句之后添加一个system()
,这样就可以知道Python命令何时完成。关于c - C-dup2 stdin使dup2 stdout和stderr停止打印,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41686807/