Output redirection using fork() and execl()

前端 未结 2 1367
谎友^
谎友^ 2020-12-01 15:09

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

相关标签:
2条回答
  • 2020-12-01 15:48

    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);
     }
    
    0 讨论(0)
  • 2020-12-01 15:53

    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()

    0 讨论(0)
提交回复
热议问题