首页 \ 问答 \ 按终止顺序打印?(Print in order of termination?)

按终止顺序打印?(Print in order of termination?)

我有一个程序产生一个随机数n,然后循环n次。

在每次迭代中,它随机化sleeptime的值,并调用fork。 子进程睡眠睡眠时间秒,然后用索引变量的值退出。

然后父级再次循环,等待每个进程终止。 当每个进程终止时,我试图注销进程的pid和childid,但这是我遇到麻烦的地方。 这些pid按顺序打印,并且childid保持为0。

我究竟做错了什么?

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

    //  Wire up the timer
    long time = elapsedTime(0);

    /*  Generate a random number between MINFORKS and MAXFORKS
     */
    unsigned int seed = generateSeed(0);
    int n = rand_r(&seed) % MAXFORKS + MINFORKS-1;

    /*  Log next step
     */
    time = elapsedTime(1);
    printf("%li: Number of forks = %i\n", time, n);

    /*  Hang on to the PIDs so we can wait for them after forking
     */
    pid_t *PIDs = (pid_t *)(malloc(sizeof(*PIDs)*n));


    /*  Fork n times
     */
    for (int i = 0; i < n ; i++)
    {
        /*  Call fork() and retain the returned identifier
         */
        pid_t processIdentifier = fork();

        /* Randomize the child sleep time
         */
        seed = generateSeed(0);
        int sleeptime = rand_r(&seed)  % MAXPAUSE + MINPAUSE;

        /*  Check for errors
         */
        if (processIdentifier == -1) {
            printf("Error: %i", errno);
        }


        if (!processIdentifier)
        {
            /*  We're in the child process,
             *  sleep and then exit with
             *  i as the error code.
             */

            usleep(sleeptime);
            _exit(i);
        }
        else
        {
            /*  We're in the parent:
             *  Store the PID and
             *  print out the results.
             */

            PIDs[i] = processIdentifier;

            time = elapsedTime(1);
            printf("%li: Child %i, pid = %i, forked, waits %i usec\n", time,  i, processIdentifier, sleeptime);

        }
    }

    /* Log next step
     */
    time = elapsedTime(1);
    printf("%li: Finished forking, going to wait.\n", time);

    /*
     *  Loop through the processes and wait for them
     *  to terminate. Then print the childid, and the
     *  the pid.
     */

    for (int i = 0; i < n; i++)
    {

        /*  Get the PID we want to track
         */
        pid_t pid = PIDs[i];

        /*  Wait for the child process
         *  and grab it's status info
         */
        int status = NULL;


        waitpid(pid, &status, 0);

        int childid = -1;
        if(WIFEXITED(status))
        {
            childid = WTERMSIG(status);
        }

        /*  Log the results
         */
        time = elapsedTime(1);
        printf("%li: Child %i, pid = %i, terminated\n", time, childid, pid);
    }

    /*  All done!
     */
    time = elapsedTime(1);
    printf("All done. It only took %li milliseconds!", time);   
}

免责声明,这是作业(链接在这里,可能随时消失) ,但我已经完成了几乎所有的作业。 我只是无法理解它的这一方面。


I've got a program which generates a random number, n, then loops n times.

On each iteration, it randomizes the value of sleeptime, and calls fork. The child process sleeps for sleeptime seconds, then exits with the value of the index variable.

The parent then loops again, waiting for each process to terminate. As each process terminates, I'm trying to log out the pid and childid of the process, but this is where I'm running into trouble. The pids are printing in order, and childid is remaining at 0.

What am I doing wrong?

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

    //  Wire up the timer
    long time = elapsedTime(0);

    /*  Generate a random number between MINFORKS and MAXFORKS
     */
    unsigned int seed = generateSeed(0);
    int n = rand_r(&seed) % MAXFORKS + MINFORKS-1;

    /*  Log next step
     */
    time = elapsedTime(1);
    printf("%li: Number of forks = %i\n", time, n);

    /*  Hang on to the PIDs so we can wait for them after forking
     */
    pid_t *PIDs = (pid_t *)(malloc(sizeof(*PIDs)*n));


    /*  Fork n times
     */
    for (int i = 0; i < n ; i++)
    {
        /*  Call fork() and retain the returned identifier
         */
        pid_t processIdentifier = fork();

        /* Randomize the child sleep time
         */
        seed = generateSeed(0);
        int sleeptime = rand_r(&seed)  % MAXPAUSE + MINPAUSE;

        /*  Check for errors
         */
        if (processIdentifier == -1) {
            printf("Error: %i", errno);
        }


        if (!processIdentifier)
        {
            /*  We're in the child process,
             *  sleep and then exit with
             *  i as the error code.
             */

            usleep(sleeptime);
            _exit(i);
        }
        else
        {
            /*  We're in the parent:
             *  Store the PID and
             *  print out the results.
             */

            PIDs[i] = processIdentifier;

            time = elapsedTime(1);
            printf("%li: Child %i, pid = %i, forked, waits %i usec\n", time,  i, processIdentifier, sleeptime);

        }
    }

    /* Log next step
     */
    time = elapsedTime(1);
    printf("%li: Finished forking, going to wait.\n", time);

    /*
     *  Loop through the processes and wait for them
     *  to terminate. Then print the childid, and the
     *  the pid.
     */

    for (int i = 0; i < n; i++)
    {

        /*  Get the PID we want to track
         */
        pid_t pid = PIDs[i];

        /*  Wait for the child process
         *  and grab it's status info
         */
        int status = NULL;


        waitpid(pid, &status, 0);

        int childid = -1;
        if(WIFEXITED(status))
        {
            childid = WTERMSIG(status);
        }

        /*  Log the results
         */
        time = elapsedTime(1);
        printf("%li: Child %i, pid = %i, terminated\n", time, childid, pid);
    }

    /*  All done!
     */
    time = elapsedTime(1);
    printf("All done. It only took %li milliseconds!", time);   
}

Disclaimer, this is homework (link here, may disappear at any time), but I've already done almost all of it. I'm just having trouble grasping this one aspect of it.


原文:https://stackoverflow.com/questions/16742907
更新时间:2022-04-03 09:04

最满意答案

安卓游戏,很多人喜欢去那种手机应用程序里下载,但其实那根本不靠谱啊,推荐给你这样一个手游排行榜,这个是18183手游排行榜,里面包含2个大榜单,18183新游期待榜和18183热门手游榜,亲可以依据具体情况去选择,这里每天都更新,现在最多人玩的游戏一看就知道了,选起来也方便,给你地址 http://top.18183.com/?=wd还有一个对应的,直接拿礼包,亲可以看看http://ka.18183.com/list_game_2188.shtml

相关问答

更多
  • 需要完整的安卓游戏开发教程的话,可以到IT学习那里下载。IT学习联盟哪里有很多关于安卓开发的教程。那里有5000GIT资源和10万IT源代码等你下载网址www.itxxlm.com。 关于如何学习android,我刚才看到一篇很不错的文章,是一个中专生介绍自己如何自学android,并找到android的工作,里面介绍了他的学习方法和学习过程,希望对你有帮助。 我是一名中专生,在学校里读的是计算机专业,但是由于学校不好大部分同学都不爱学习来这里几乎大部分都是在混日子的,虽然我中考的成绩不差,但是因为家里穷考 ...
  • 你好 主要是手机配置问题 一般双核1Gz 内存上512MB 这样的手机玩各种大型游戏都不会卡 廉价推荐:华为、中兴、小米 贵价:三星 (不推荐酷派手机!系统缺陷较多!无重力遥感的底线附加功能) 请采纳谢谢
  • 你好,安卓手机 是使用 Google公司开发的操作系统(android)的手机。现广泛运用在社会上,手机目前有多个系统,例如我所知道的:Android、iOS、Firefox OS、YunOS、BlackBerry、Windows phone、symbian、Palm、BADA、Windows Mobile、ubuntu,Sailfish OS(给予Mego系统开发的) 详情请见——百度百科:http://baike.baidu.com/link?url=iG3iBoUNoa9dQPp9NJTffrATnL ...
  • 在应用宝上有安卓版本的rookie软件 你可以从应用宝下载到手机看能否正常安装使用 应用宝提供的安卓手机软件很多 很多移植的工具,汉化版本的app等使用起来都很方便呢 各种网站上提供的比较出色的app都会在应用宝陆续登陆 因为是开源的平台,能够集合更多的资源,实现更多的功能 相机软还有很多的素材库,滤镜等素材可以使用 回答不容易,希望能帮到您,满意请帮忙采纳一下,谢谢
  • 方法: 1、今天要说的是手机APP【迅捷录屏大师】,但是如果想投屏到电脑上,手机和电脑端都需要同时运行这款软件,这样就可以把手机屏幕投屏到电脑显示器上; 2、打开电脑端不需要做什么,等待手机中的调节好就行,在手机中选择投屏,可以开启“自动录屏”,意思就是不但可以投屏还可以录制下来,在投屏中点击扫一扫即可和电脑完成连接; 3、在投屏期间录制的内容在视频库中可以看到,期间不想投屏了在手机和电脑端都可以关闭投屏功能,电脑端叉掉就可以了,手机端点击“停止投屏”。 4、以上是手机屏幕投屏到电脑显示器上的方法,希望可以 ...
  • 如果你只是想在电脑上用安卓软 件,我推荐用一个软件! 建议:装这个软件前先装好Java,反正模拟也要的! BlueStacks – 可直接在电脑上运行Android 软件游戏的模拟器!瞬间将电脑变成安卓手机(不是真的变,是通过这个软件玩安卓各种游戏应用) BlueStacks支持多国语言包含简体中文,支持惯性加速(等于用鼠标实现更真实的手指触摸效果),并且也预装了水果忍者、涂鸦切割、家园、Evernote等知名游戏或应用,让你畅玩到底。当然,它里面还有一些应用商店等,你可以下载更多更好玩的东西…… Blue ...
  • 哈哈、我也是比较喜欢玩游戏、小时候用电视、两年前用psp、今年换成了安卓手机、不过换成安卓手机之后3D游戏就不怎么完了、玩一些经典的小游戏:小羊快跑、水果忍者、连连看等都很不错、要说手机手机排行榜的话首先就要说愤怒的小鸟、植物大战僵尸等一些从iphone上复制过来的经典游戏就不一一说明了、不过楼主要是比较喜欢安卓手机游戏的话、建议去安卓园下载,里面推荐的都是top100的游戏、非常的不错
  • 经典安卓手机游戏排行榜: 除了风靡全球的愤怒的小鸟、还有很多经典游戏值得大家去玩:(下载一下游戏都可以去安卓园) 【暗影时代】 Shadow Era为一款魔幻风格的免费的集换卡片策略游戏,卡牌设计华丽,游戏规则严谨富有策略,但又简单易学,节奏很快,适合随时拿出来玩两局。 【傲气雄鹰 】 一款不错的射击战略游戏。 【超音速飞行】 款以未来世界为背景的快节奏竞速类游戏。通过比赛的胜利可以解除新的赛道及飞船。游戏中拥有独特的游戏模式,不同的赛道,飞船,武器。生涯模式中拥有22个事件,8种完全不同背景的赛道 ...
  • 手机游戏永远是娱乐消遣的最佳选择,在android 上表现的更加完美。以下为笔者最新整理的6款小弟认为的最适合的超可爱游戏,华丽可爱,充满着梦幻乐趣。 会说话的汤姆猫免费版 汤姆是一只宠物猫,他可以在您触摸时作出反应,并且用滑稽的声音完整地复述您说的话。您可以抚摸他,用手指戳他,用拳轻打他,或捉他的尾巴。 摇汽水 世界上最好玩的要可乐游戏。 请紧握你的手机,尽情摇摆,看多就能够将可乐摇爆。提醒,不要因为好玩给小孩子玩,手机甩飞就是杯具了。 电子宠物 游戏让你领养一只小狗,然后逐渐赔偿它成为一个乖巧的宠物,需 ...
  • 安卓手机游戏[2023-08-17]

    推荐给你个专用安卓手机软件:91手机助手。 手机连接电脑就能使用,有很多免费是安卓软件和游戏下载,可以直接安装到手机,而且保证无毒,还可以管理手机数据。

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)