使用fork()和execl()的输出重定向

编程入门 行业动态 更新时间:2024-10-23 16:22:17
本文介绍了使用fork()和execl()的输出重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想使用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()的输出重定向

本文发布于:2023-10-09 06:18:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1474936.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:重定向   fork   execl

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!