Redirecting output using fork () and execl ()

I want to use fork () to create a new process in my program. The new process will have only one task: redirect mouse input to the serial port. I successfully checked the following command in the terminal window: hexdump / dev / input / mice> / dev / ttyS0

So far, I have managed to use fork to create a child process, but my problem is that I cannot get my execl () method to work correctly:

execl("/usr/bin/hexdump", "hexdump", "/dev/input/mice > /dev/ttyS0", (char*) NULL);

I also tried other options, for example:

execl("/usr/bin/hexdump", "hexdump", "/dev/input/mice", ">", "/dev/ttyS0", (char*) NULL);

But always with the same result, the value of output is 1 (general error).

It is also worth mentioning that I managed to get it to work using the popen () method, where you can enter the command in the same way as in the terminal. The problem with popen () is that I did not find a good way to complete the process. With fork (), I get the PID and can end the process using:

kill(pid, SIGKILL);

This is a requirement because I should be able to stop and restart output redirection as needed while the program is running.

+4
source share
2 answers

You cannot redirect in this way.

If you want to redirect stdoutfor the process that you are going to exec, you need to openspecify the path and dup2the corresponding file descriptor.

Example:

 if (!(pid = fork()) 
 {
     int fd = open("/dev/ttyS0", O_WRONLY);
     dup2(fd, 1);  // redirect stdout
     execl("/usr/bin/hexdump", "hexdump", "/dev/input/mice", NULL);
 }
+8

" > ". (bash ). execl() hexdump

system()

system("hexdump /dev/input/mice > /dev/ttyS0")

.

pid , fork(), system() execl()

+1

All Articles