首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C中阻塞的进程

C中阻塞的进程
EN

Stack Overflow用户
提问于 2012-12-03 01:11:08
回答 2查看 2.3K关注 0票数 1

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

我试过了,但我的C语言知识不是很好。代码不会打印任何内容。

这就是它:

代码语言:javascript
运行
复制
#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);
}

这应该很容易,因为这只是一个小程序被阻塞了,但我想我是在兜圈子。有什么建议吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-12-03 01:27:32

sleep()有一个参数:休眠的秒数。当您省略它时,它往往会立即返回。

另外,wait()接受int *,而不是int

试试这个:

代码语言:javascript
运行
复制
#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()的调用之上,因此您应该在父级阻塞等待子级之前看到它。

编辑:另外,包含<unistd.h>。虽然对于程序的工作(在大多数系统上)并不是严格要求的,但这样做可以为您提供更好的编译时错误报告,例如缺少和/或键入错误的函数参数。

票数 3
EN

Stack Overflow用户

发布于 2012-12-03 01:24:11

man sleep

man wait

您应该在sleep()中提供秒数作为参数。

对于waitsleep,包含<unistd.h>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13671628

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档