我想使用fork()在我的程序中产生一个新的进程。新进程将只有一个任务:将鼠标输入重定向到串行端口。我在终端窗口中成功测试了以下命令: hexdump / dev / input / mice> / dev / ttyS0
I want to use fork() to spawn off a new process in my program. The new process will have only one task: To redirect the mouse input to a serial port. I have tested the following command with success in a terminal window: hexdump /dev/input/mice > /dev/ttyS0
已经设法使用fork创建一个子进程,但我的问题是,我似乎无法让我的execl()方法正常工作:
So far I have managed to use fork to create a child process, but my problem is that I can't seem to get my execl() method to work properly:
execl("/usr/bin/hexdump", "hexdump", "/dev/input/mice > /dev/ttyS0", (char*) NULL);我也尝试过其他变体,例如:
I have tried other variants also, like this:
execl("/usr/bin/hexdump", "hexdump", "/dev/input/mice", ">", "/dev/ttyS0", (char*) NULL);但总是具有相同的结果,退出值为1(一般错误)。
But always with the same result, an exit value of 1 (general error).
还值得一提的是,我已经通过使用popen()方法使它工作,你可以在终端中输入命令。 popen()的问题是我没有找到一个好的方法来终止进程。 使用fork()获取PID,并可以使用以下命令终止进程:
It's also worth mentioning that I have managed to make it work by using the popen() method, where you can type the command exactly like you would have done in a terminal. The problem with popen() is that I have not found a good way for terminating the process. With fork() I get the PID, and can terminate the process by using:
kill(pid, SIGKILL);这是一个要求,因为我必须能够根据需要停止和重新启动输出重定向
This is a requirement, as I have to be able to stop and restart the output redirection as desired while the program is running.
推荐答案您不能以这种方式执行重定向。
You cannot perform redirection in this way.
如果您要为要处理 exec 的进程重定向 stdout ,则需要打开路径和 dup2 到相应的文件描述符。
If you want to redirect stdout for a process you're about to exec, you need to open the path and dup2 it onto the appropriate file descriptor.
if (!(pid = fork()) { int fd = open("/dev/ttyS0", O_WRONLY); dup2(fd, 1); // redirect stdout execl("/usr/bin/hexdump", "hexdump", "/dev/input/mice", NULL); }
更多推荐
使用fork()和execl()的输出重定向
发布评论