Home  >  Article  >  System Tutorial  >  Linux shell and process

Linux shell and process

WBOY
WBOYOriginal
2024-06-12 22:46:30676browse

Linux之shell 和进程

Run a few commands here:

Print login process (always exists until login and exit) ID

george.guo@ls:~$ echo $PPID
3411
george.guo@ls:~$ ps -aux | grep 3411
george.+ 3411 0.0 0.0 99004 4520 ? S 11:00 0:00 sshd: george.guo@pts/46

Print the shell process forked by the login process (always exists until login and exit)

george.guo@ls:~$ echo $$
3412
george.guo@ls:~$ ps -aux | grep 3412
george.+ 3412 0.5 0.0 21380 5120 pts/46 Ss 11:00 0:00 -bash

As can be seen from the above commands:

The login process ID is 3411, which creates the bash shell subprocess 3412. Future script execution,

3412 We call it the main shell here, which will start the subshell process to process the script.

(Note: In bash, the PID of the subshell process is stored in a special variable '$$', and the PPID stores the ID of the subshell's parent process.)

Let’s write two small programs to verify:

george.guo@ls:~$ cat yes.c

#include 
#include 
#include <sys/types.h>
#include 

int main()
{
        pid_t pid;
        pid_t ppid;

        pid = getpid();
        ppid = getppid();
        system("./test");       //system will fork a process for exec ./test
        printf("yes pid = %d, yes ppid =  %d\n", pid, ppid);
}

george.guo@ls:~$ cat test

#!/bin/bash
echo "PID of this script: $$"
echo "test's PPID(system's fork id) = $PPID"
echo "tests's pid = $$"

The running results are as follows:

george.guo@ls~$ ./yes

PID of this script: 6082
tests PPID(system's fork id)= 6081
echo tests self pid is 6082
yes PID = 6080, yes PPID = 3412

It can be seen that the parent process ID of the yes process is 3412, which is the bash shell child process of the login process fork and the main shell. This is because

yes is executed by the main shell. yes The process ID is 6080, call system, fork and the subshell ID is 6081.

For system calls:

Using system() to run commands requires creating at least two processes. One is used to run the shell (here its ID is 6081),

The other one or more are used for the command executed by the shell (here is a subshell, which is the script test itself).

The process ID of script test itself is 6082.

The above is the detailed content of Linux shell and process. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn