【问题标题】:How to use fork and wait to run child process indefinitely?如何使用 fork 并无限期地等待运行子进程?
【发布时间】:2019-11-11 21:56:09
【问题描述】:

我正在创建一个程序,允许用户输入单词的长度,并返回与该长度对应的单词数。

这方面我已经完成了

我的问题如下:我应该有一个子进程来计算并返回与长度对应的单词,然后再次要求用户输入另一个长度。但是,如果某个长度的字符串为0,我应该让子进程无限期地重做计数,只通过单独的终端终止而不终止父进程。

感谢任何帮助。

我的代码如下

#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
using namespace std;

int WordsCount(char *string,int len){

    int count=0,Wordcount=0;

    while(*string){

        //Checks for Delimeter
        if (*string== ' ' || *string== ',' || *string== '\t' || *string== '\n' || *string== '.' || *string== '!' || *string == '\0'){

            if (count==len){ // Checks If calculated length equals to User given length
                Wordcount++;
                count=0;
                string++;
            }
            else{
                count=0;
            }
        }
        else{
            count++;
        }

        string++;
    }
    return Wordcount; //Returns The Final Count of Words
}

int main()
{
    const char string[] = "Maids table how learn drift but purse stand yet set. Music me house could among oh as their."
    "Piqued our sister shy nature almost his wicket. Hand dear so we hour to. He we be hastily offence effects he service."
    "Sympathize it projection ye insipidity celebrated my pianoforte indulgence. Point his truth put style."
    "Elegance exercise as laughing proposal mistaken if. We up precaution an it solicitude acceptance invitation."
    "Acceptance middletons me if discretion boisterous travelling an. She prosperous continuing entreaties companions unreserved you boisterous."
    "Middleton sportsmen sir now cordially ask additions for. You ten occasional saw everything but conviction. Daughter"
    "returned quitting few are day advanced branched. Do enjoyment defective objection or we if favourite. At wonder afford so danger cannot former seeing."
    "Power visit charm money add heard new other put. Attended no indulged marriage is to judgment offering landlord. Parish so enable innate in formed missed."
    "Hand two was eat busy fail. Stand smart grave would in so. Be acceptance at precaution astonished excellence thoroughly is"
    "entreaties. Who decisively attachment has dispatched. Fruit defer in party me built under first. Forbade him but savings"
    "sending ham general. So play do in near park that pain.";

    int Length;

    printf("Enter Word Length?\n");

    scanf("%d",&Length);           //Reading Length of the word from User

    int result = WordsCount(string,Length);   // Return Count Storing.

    printf("Count = %d\n",result);

    return 0;
}

【问题讨论】:

  • 您应该避免使用变量名称,例如string。如果您切换到 C++ 编译器,它可能会给您带来问题。
  • 欢迎您。很高兴我能帮上忙。

标签: c linux fork


【解决方案1】:

我不确定,但请尝试一下。

    pid_t ret;
    int w,status;
ret = fork();
if(ret==-1){
    perror("Fork");
}
else if(ret==0) {
    printf("Enter Word Length?\n");
    scanf("%d",&length);
    int result=WordsCount(string,Length);
    if (result==0) {
        exit(1);
    }else{
        printf("Count = %d \n",result);
    }
}else{
    printf("Enter Word Length?\n");
    scanf("%d",&length);
    w = wait(&status);
    int result = WordsCount(string,Length);
}

【讨论】:

  • 并在 else 语句的两端添加 printf("Count= %d",result)。
  • 点评来源: 您好,请不要只回答源代码。尝试对您的解决方案如何工作提供一个很好的描述。请参阅:How do I write a good answer?。谢谢
【解决方案2】:

我不确定是否清楚地了解您想要达到的目标,但以防万一... 我认为无限运行的线程/进程是一个错误,除非某些东西可以在“生命”期间改变它的行为。 (不仅等待人为动作)

不过,我认为您应该考虑使用线程而不是分叉。这将确保如果父进程结束或被杀死,所有线程都会死亡,否则您的子进程可以继续运行,直到有人杀死它们。 (人为操作或重启)

无论您选择什么,您都可以通过 google 搜索轻松找到代码示例。 了解如何从另一个终端中断子线程/进程,没有简单的方法,因为它将在后台启动。

困难的方法:让孩子控制一个监听套接字并在收到消息时退出。

一种更简单的方法:让孩子在启动时创建一个文件,并控制该文件在每个循环中仍然存在。如果文件被删除,让孩子退出。

另一种方式(更优雅)可能是使用 linux 信号。实现一个信号侦听器并在它捕获到 SIGUSR1 或 SIGUSR2 信号时使其停止。 请参阅“man 2 signal”以获得一些帮助。缺点是如果您的父进程/线程启动多个子进程,它们将在收到信号后全部停止。(无法停止特定的子进程)

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    • 2010-09-21
    • 1970-01-01
    • 2011-06-21
    相关资源
    最近更新 更多