Describe the use of system of function and vfork of function in C language

  • 2020-04-02 03:18:16
  • OfStack

C language system() function: execute the shell command
The header file:


 #include <stdlib.h>

Definition function:


int system(const char * string);

Function description: system() will call fork() to produce a child process, by the child process to call /bin/sh-c string to execute the command represented by the parameter string string, this command will return to the original calling process.

The return value:
1. If system() fails when calling /bin/sh, it returns 127, and other reasons for failure return -1.
2. If the parameter string is NULL, a non-zero value is returned.
3. If the system() call is successful, it will finally return the return value after executing the shell command, but this return value may also be 127 returned by the failure of the system() call to /bin/sh, so it is better to double-check errno to confirm the execution is successful.

Note: do not use system() when writing a program with SUID/SGID permissions. System () inherits environment variables, which can cause problems with system security.

sample


#include <stdlib.h>
main()
{
 system("ls -al /etc/passwd /etc/shadow");
}

Perform:


-rw-r--r-- 1 root root 705 Sep 3 13 :52 /etc/passwd
-r--------- 1 root root 572 Sep 2 15 :34 /etc/shadow

C vfork() function: creates a new process

The header file:


#include <unistd.h>

Definition function:


pid_t vfork(void);

Function description:
Vfork () produces a new child that copies the parent's data and stack space and inherits the parent's user code, group code, environment variables, open file code, working directory, and resource constraints.

Linux USES copy-on-write(COW) technology. Only when one of the processes tries to modify the space to be copied will it actually copy. Since the inherited information is copied, it does not refer to the same memory space.

In addition, child processes do not inherit the parent process's file locks and unprocessed signals.

Note: Linux does not guarantee that child processes will execute earlier or later than their parents, so be aware of deadlocks or race conditions when writing programs.

Return value: if vfork() succeeds, the newly created child code (PID) is returned in the parent process, and 0 in the newly created child process.

Error code:
1. EAGAIN: out of memory.
2. ENOMEM: insufficient memory to configure the data structure space required by the core.

sample


#include <unistd.h>
main()
{
 if(vfork() == 0)
 {
  printf("This is the child processn");
 }
 else
 {
  printf("This is the parent processn");
 }
}

Perform:


this is the parent process this is the child process


Related articles: