gpt4 book ai didi

c - c中的阻塞进程

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:57:58 24 4
gpt4 key购买 nike

我正在编写一些代码来创建一个阻塞然后结束的进程,我必须能够使用 ps 查看阻塞状态。

我尝试过这个,但我的 C 知识并不好。该代码不打印任何内容。

这里是:

#include <stdio.h>
#include <stdlib.h> //exit();
#include <unistd.h> //sleep();

int main(int argc, char *argv[]) {
createblocked();
}

int pid;
int i;
int estado;

void createblocked() {
pid = fork();

switch( pid ) {
case -1: // pid -1 error ocurred
perror("error\n");
break;
case 0: // pid 0 means its the child process
sleep(); // we put the child to sleep so the parent will be blocked.
printf("child sleeping...");
break;
default: // !=0 parent process
// wait function puts parent to wait for the child
// the child is sleeping so the parent will be blocked
wait( estado );
printf("parent waiting...\n");
printf("Child terminated.\n");
break;
}
exit(0);
}

这应该很容易,因为只有一个小程序会被阻塞,但我认为我在原地打转。有什么建议吗?

最佳答案

sleep()接受一个参数: sleep 的秒数。当您忽略它时,它往往会立即返回。

还有 wait()需要 int * ,不是 int .

试试这个:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
createblocked();
}

int pid;
int i;
int estado;

void createblocked() {
pid = fork();

switch(pid)
{
case -1: // pid -1 error ocurred
perror("error\n");
break;
case 0: // pid 0 means its the child process
printf("child sleeping...\n");
sleep(500); // we put the child to sleep so the parent will be blocked.
break;
default: // !=0 parent process
// wait function puts parent to wait for the child
// thechild is sleeping so the parent will be blocked
printf("parent waiting...\n");
wait(&estado);
printf("Child terminated.\n");
break;

}
exit(0);
}

注意:我还移动了 printf("parent waiting...\n") 上方wait() 的调用,所以你应该在父阻止等待 child 之前看到它。

编辑:另外,包括 <unistd.h> .虽然不是严格要求程序运行(在大多数系统上),但这样做将为您提供更好的编译时错误报告,例如缺少和/或错误类型的函数参数。

关于c - c中的阻塞进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13671628/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com