In Linux, the int system (const char * command) function often uses system (). Recently, the program that needs to be called in sequence is equivalent to executing system () twice (); 1 system ("tar-zcvf xxx.tar.gz xxx"); // The first step is to run the package 2 system ("tar-zxvf xxx.tar.gz"); // The first step is to run the package, unpackage
Similar to the preceding method, the second step must be executed after the first step is completed. Otherwise, the second step cannot be executed, or
The result is incorrect. Now you have questions? System (); is the library function calling blocked?
Man system shows that system is a library function, not a system call. And you can know that system (); is a blocking call,
That is to say, in the above Code, only after the tar command called by the system in the first step is returned after packaging is completed, the second
In this way, we can solve the problem we first mentioned and create a program for synchronous sequential execution. The question of www.2cto.com is coming again. What if we want to make an asynchronous one? What should I do? That is to say, assume that you have the following requirements: 1 system ("tar-zcvf xxx.tar.gz xxx"); // package xxx in the first step, step 2 system ("tar-zcvf yyy.tar.gz yyy"); // package yyy in step 2 without dependency on Step 1
I have referred to the source code of the rpm program and used fork (); system call to let the sub-process execute "tar-zcvf xxx.tar.gz xxx ",
Then the parent process fork a sub-process to execute "tar-zcvf yyy.tar.gz yyy ". This solves the asynchronous problem. The problem arises again. What should the parent process do next? Now that fork is running, we must do wait. Is it using wait (); or waitpid? Www.2cto.com 1 pid_t wait (int * status); 2 pid_t waitpid (pid_t pid, int * status, int options );
Waitpid can be said to be the wait encapsulation. There are two more parameters: keton, pid, and options. It is better to use waitpid here. In the next loop, the waitpid sub-processes are constantly removed, and the WNOHANG
Option, of course, you can add a sleep (1) to reduce the cpu usage.