In Linux, use c ++ to call shell commands.
1: system ()
Statement:
Extern int system (const char * _ command) _ wur;
Function Description: fork () is called to generate sub-processes. The sub-processes execute specific commands. During the system call, SIGG
HID signals are shelved, but SIGINT and SIGQUIT are ignored.
For returned values, if system () fails to call/bin/sh, 127 is returned, and other causes of failure are returned-
2: popen
Extern FILE * popen (const char * _ command, const char * _ modes) _ wur;
Popen () also calls fork () to generate a sub-process, and then calls/bin/sh-c from the sub-process
Command. The type parameter can be read by using "r", "w"
Indicates writing. According to this type value, popen () creates a standard pipe to connect to the sub-process
Output device or standard input device, and then return a file pointer. Then the process will be available
This file pointer is used to read the output device of a sub-process or to write data to a sub-process.
Enter the device. In addition, all functions that use FILE * operations can also
In addition to fclose.
3. Use vfork () to create a sub-process and then call the exec function family.
First, we will introduce the difference between the vfork function and the fork function:
Difference between fork and vfork
1. fork needs to copy the data segment of the parent process, while vfork does not need to completely copy the data segment of the parent process. Before the child process does not call exec or exit, the child process shares the data segment with the parent process.
2. fork does not limit the execution sequence of parent and child processes. In a vfork call, the child process runs first and the parent process hangs until the child process calls exec or exit, the execution sequence of parent and child processes is not limited.
To end a sub-process, use _ exit (0) instead of exit (0 ). This is because _ exit (0) does not perform any operations on the standard I/O Stream when the process ends. Exit (0) will close all standard I/O streams of the process.
#include<unistd.h>main(){char * argv[ ]={“ls”,”-al”,”/etc/passwd”,(char*) };if(vfork() = =0){execv(“/bin/ls”,argv);}else{printf(“This is the parent process\n”);}}