Non-blocking version of system()

后端 未结 6 632
傲寒
傲寒 2020-12-09 03:24

I want to launch a process from within my c program, but I don\'t want to wait for that program to finish. I can launch that process OK using system() but that always waits.

相关标签:
6条回答
  • 2020-12-09 03:34

    In the end, this code appears to work. Bit of a mis-mash of the above answers:

    pid = fork();
    
    if (!pid)
    {
        system("command here &");
    }
    
    exit(0);
    

    Not quite sure why it works, but it does what I'm after, thanks to everyone for your help

    0 讨论(0)
  • 2020-12-09 03:37

    You could use posix_spawnp() function. It's much similar to system() than the fork and exec* combination, but non-blocking.

    0 讨论(0)
  • 2020-12-09 03:39

    Why not use fork() and exec(), and simply don't call waitpid()?

    For example, you could do the following:

    // ... your app code goes here ...
    pid = fork();
    if( pid < 0 )
        // error out here!
    if( !pid && execvp( /* process name, args, etc. */ )
        // error in the child proc here!
    // ...parent execution continues here...
    
    0 讨论(0)
  • 2020-12-09 03:43

    The normal way to do it, and in fact you shouldn't really use system() anymore is popen.
    This also allows you to read or write from the spawned process's stdin/out

    edit: See popen2() if you need to read and write - thansk quinmars

    0 讨论(0)
  • 2020-12-09 03:44

    One option is in your system call, do this:

     system("ls -l &");
    

    the & at the end of the command line arguments forks the task you've launched.

    0 讨论(0)
  • 2020-12-09 03:47

    How about using "timeout" command if you are looking for your command to exit after a specific time:

    Ex: system("timeout 5 your command here"); // Kills the command in 5 seconds if process is not completed

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