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 follo
You cannot perform redirection in this way.
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.
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);
}
The problem seems to be the ">" argument. This symbol is specific to the shell (bash or dash in your case). But execl()
call does not invoke the shell and passes the arguments to the hexdump
As a possible solution I can propose using of system()
call
Like system("hexdump /dev/input/mice > /dev/ttyS0")
This will simulate the behaviour of your command line experiment.
And to get the pid of your process you can continue doing fork()
, just call the system()
in place of execl()