21xrx.com
2024-06-02 23:20:19 Sunday
登录
文章检索 我的文章 写文章
如何创建、启动、暂停、恢复和终止进程等问题
2023-07-10 12:56:59 深夜i     --     --
进程 创建 启动 暂停 恢复 终止

进程是操作系统中的基本概念之一,可以看做是正在执行的一个程序或任务。每个进程都有一定的资源,如内存、CPU时间等。在操作系统中,我们可以对进程进行创建、启动、暂停、恢复和终止等操作,以达到控制进程的目的。

如何创建进程?

在Linux系统中,我们可以使用fork()系统调用创建新的进程。fork()会在当前进程中复制一个子进程。子进程和父进程拥有相同的代码和环境变量,但是fork()的返回值在两个进程中是不同的。在子进程中返回0,在父进程中返回子进程的PID。例如:


#include <stdio.h>

#include <unistd.h>

int main() {

 pid_t pid;

 pid = fork();

 if (pid < 0) {

  printf("Error: Failed to fork\n");

 } else if (pid == 0) {

  printf("This is the child process, PID = %d\n", getpid());

 } else {

  printf("This is the parent process, PID = %d, child PID = %d\n", getpid(), pid);

 }

 return 0;

}

如何启动进程?

在Linux系统中,我们可以使用exec()系列函数启动一个新进程。exec()会取代当前进程的代码和数据段,并执行新的程序。例如:


#include <stdio.h>

#include <unistd.h>

int main() {

 printf("This is the original process, PID = %d\n", getpid());

 execlp("ls", "ls", NULL);

 printf("This line will not be executed\n");

 return 0;

}

以上代码会调用ls命令,列出当前目录下的文件。注意,当exec()成功时,原进程的代码段和数据段都会被新程序替换,因此原进程的代码都不会再被执行。

如何暂停和恢复进程?

在Linux系统中,我们可以使用kill()系统调用向进程发送信号。SIGSTOP是一个可以暂停进程的信号,SIGCONT是一个可以恢复进程的信号。例如:


#include <stdio.h>

#include <unistd.h>

#include <signal.h>

int main() {

 pid_t pid;

 pid = fork();

 if (pid < 0) {

  printf("Error: Failed to fork\n");

 } else if (pid == 0) {

  printf("This is the child process, PID = %d\n", getpid());

  while (1) {

   printf("Child is running\n");

   sleep(1);

  }

 } else {

  printf("This is the parent process, PID = %d, child PID = %d\n", getpid(), pid);

  sleep(3);

  printf("Parent stops the child process\n");

  kill(pid, SIGSTOP);

  sleep(3);

  printf("Parent resumes the child process\n");

  kill(pid, SIGCONT);

  sleep(3);

  printf("Parent terminates the child process\n");

  kill(pid, SIGTERM);

 }

 return 0;

}

以上代码会创建一个子进程,该子进程会不断输入一行文字。在父进程中,会先暂停子进程,然后等待一段时间,再恢复子进程。最后,父进程会终止子进程。

如何终止进程?

在Linux系统中,我们可以使用kill()系统调用向进程发送信号。SIGTERM是一个可以终止进程的信号。例如:


#include <stdio.h>

#include <unistd.h>

#include <signal.h>

int main() {

 pid_t pid;

 pid = fork();

 if (pid < 0) {

  printf("Error: Failed to fork\n");

 } else if (pid == 0) {

  printf("This is the child process, PID = %d\n", getpid());

  while (1) {

   printf("Child is running\n");

   sleep(1);

  }

 } else {

  printf("This is the parent process, PID = %d, child PID = %d\n", getpid(), pid);

  sleep(5);

  printf("Parent terminates the child process\n");

  kill(pid, SIGTERM);

 }

 return 0;

}

以上代码会创建一个子进程,该子进程会不断输入一行文字。在父进程中,会等待5秒后终止子进程。注意,当我们使用SIGKILL时,进程会立即终止,且不会有任何机会清空缓冲区或关闭文件等资源。因此,应尽量使用SIGTERM信号进行进程终止。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复