Linux process exec family functions and fork, system, popen.

Today, I learned about the use of exec with fork and the use of system and popen in the Linux process.
For example, I want to make a file similar to when a client accesses us to modify the value of a file.
1. The combination of exec and fork:

There is a file called file.
Content:
Insert picture description here
I want to create a process similar to when someone connects to the server, I create a child process, and then modify the value of BB in the file file to 5;

Modify file value code:
Insert picture description here
This operation can modify the value in the file file.

Use the combination of exec and fork:
Insert picture description here

This will allow the child process to modify the file configuration.

Operation result:
Insert picture description here
file content:
bold style, Insert picture description here
so the modification is successful

**Note:** After exec runs successfully, it will run the amendFile program, and will not execute the following code.

2. System function
header file:

#include<stdio.h>

prototype:

 int system(const char *command);

Return value:
1. If successful, it returns the status value of the process
2. When sh cannot be executed. Return 127
3. Return -1 on failure

For example, let's make it ls
code:

Insert picture description hereResults:
Insert picture description here
Compared with exec, this system:
1. The system is simpler and rude
2. After the system is executed, it will continue to the original program. And exec will not.

Three, popen function
header file:

 #include <stdio.h>

prototype:

 FILE *popen(const char *command, const char *type);
 int pclose(FILE *stream);

**command:** is a pointer to a NULL-terminated shell command string. This command will be passed to bin/sh with the -c flag, and the shell will execute the command.
type: "r" (the file pointer is connected to the standard output of command)
"w" (the file pointer is connected to the standard input of command)

Compared with system advantages:

popen can get the output of the run

For example, like opening the "ps" command with system, we want to store the content displayed by the ps command in a file called file.
** Idea: .** Use popen to execute the command ps and then we define a variable to store the content in the variable. Then we open the file file and write the contents of the variable into the file file.

Code:
Insert picture description here
Run:
Insert picture description here
Result:
Insert picture description here
This writes successfully.

Guess you like

Origin blog.csdn.net/weixin_47457689/article/details/107711500