简体   繁体   English

创建一个进程的 C 程序,该进程被阻塞直到终止

[英]C program that creates a process that it is blocked till its termination

How do I create a process in C and play with it's state?如何在 C 中创建一个进程并使用它的状态?

  • I would like to know how to create a process.我想知道如何创建一个进程。
  • I would like to know how to put this process in Blocked state.我想知道如何将此进程置于阻塞状态。
  • I would like to know how to put this process in a Zombie state.我想知道如何将这个过程置于僵尸状态。

A guide on how to work with processes on C would be helpfull I just can't find it around.关于如何在 C 上使用进程的指南会很有帮助,我只是找不到它。 This way I could answer those questions myself.这样我就可以自己回答这些问题了。

I've been playing around with ps to see the state of a process but dont really know how to start.我一直在玩 ps 来查看进程的状态,但真的不知道如何开始。

Am working on Linux, sorry for my English.我在 Linux 上工作,对不起我的英语。

Create a child process using fork() - your program itself runs in a process anyway使用 fork() 创建一个子进程 - 您的程序本身无论如何都在一个进程中运行

Put process in "blocked" state:- use sleep() or issue a blocking write() - read manpages for more info - dunno what exactly you mean by 'blocked' here将进程置于“阻塞”状态:- 使用 sleep() 或发出阻塞 write() - 阅读联机帮助页以获取更多信息- 不知道这里的“阻塞”究竟是什么意思

Creating a zombie - fork() and then exit the program.创建一个僵尸 - fork() 然后退出程序。 You can "see" the zombie from ps你可以从ps中“看到”僵尸

if you throw out your understanding of typical parent child processes, it becomes simple如果你抛开对典型父子进程的理解,事情就变得简单了

childpid=fork();
switch (childpid){
case 0 : //normally considered the child, but we will use it to continue on
     finish_program();
     return(0);
case -1 : //error occurred
default : //normally considered the parent, but our "blocked" process
     wait(childpid); //waits for the child process to terminate
     dostuff();
}

the parent is blocked until the child terminates父进程被阻塞,直到子进程终止

normally you would use semaphores and shared memory to block a process, but this is a good start通常你会使用信号量和共享内存来阻塞一个进程,但这是一个好的开始

@user1869399 - I think you asked a very good question, and I think Bug Catcher gave a very good answer. @ user1869399 - 我认为你问了一个很好的问题,我认为 Bug Catcher 给出了一个很好的答案。

Key to Bug Catcher's suggestion about creating a "zombie" is forking a process without "cleaning up" after it exits (ie failing to call "waitpid()"). Bug Catcher 关于创建“僵尸”的建议的关键是在退出后不“清理”的情况下分叉进程(即未能调用“waitpid()”)。

Here is a very good link on Linux process states:这是一个关于 Linux 进程状态的非常好的链接:

Also, look at the "notes" section in the "man page" for waitpid():另外,请查看 waitpid() 的“手册页”中的“注释”部分:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM