【问题标题】:How to make this C function execute continuously? [closed]如何让这个 C 函数连续执行? [关闭]
【发布时间】:2019-10-22 10:56:41
【问题描述】:

我有一个 C 程序,它从命令行获取输入,处理输入,生成文件并终止。

例如 myprogram.c 类似于:

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

//do something with the input
// and generate a file

exit(0);
}

我目前的输入如下: echo -n abcd | myprogram.c

我希望程序做的不是在一个输入后终止,它应该继续执行并等待下一个控制台输入生成下一个文件,依此类推。

有人可以指导我吗?

【问题讨论】:

  • 如果你想让某件事重复发生,请使用循环。如果您永远不希望它停止,请使用无限循环,即条件始终为真的循环。而且你不需要把exit(0)放在main的末尾,这完全是多余的。
  • @Useless,所以基本上将功能包装在while(1)?我如何检查程序是否终止以及如何提供连续输入来测试它?如前所述,目前我的输入格式为echo -n abcd | myprogram.c
  • @rb-93 结束条件是什么?

标签: c


【解决方案1】:

您可以使用while 循环:

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

bool function(char *input)
{
    // do something with the input
    // and generate a file

    // example:
    if (strcmp(input, "exit") == 0)
        return true;

    printf("I did something with '%s'\n", input);
    return false;
}

int main(int argc, char *argv[])
{
    if (argc < 2)
    {
        printf("Usage: program_name <argument>.");
        return 1;
    }

    function(argv[1]);

    bool exit = false;
    while (!exit)
    {
        char input[32];
        scanf("%s", &input);
        exit = function(input);
    }
    return 0;
}

【讨论】:

  • 我能不能把整个功能都包装在 while 循环中,而不是写两次相同的东西?
  • 是的,检查我更新的代码
【解决方案2】:

您要做的是在重定向后将stdin 返回到您的控件(终端输入)。根据C-FAQ,你不能以便携的方式做到这一点:

没有可移植的方式来做到这一点。 在 Unix 下,您可以打开特殊文件 /dev/tty。在 MS-DOS 下,您可以尝试打开“文件”CON,或使用例程或 BIOS 调用(例如 getch),无论输入是否被重定向,它们都可能转到键盘。

但是,如果可移植性不是问题,我们可以尝试一些变通方法(不是最佳的):

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

int main(int argc, char *argv[])
{
    char buf[1001], fname[10];
    FILE *fp;
    int i = 0;

    while(1) {
        if(fgets(buf, 1000, stdin)) {
            sprintf(fname, "mf%d", i++);

            if(!(fp = fopen(fname, "w"))) {
                perror("fopen");
                continue;
            }

            fprintf(fp, buf);
            fclose(fp);
        }

        if(!(stdin = fopen("/dev/tty", "r"))) {
            perror("stdin");
            exit(0);
        }
    }


    return 0;
}

问题是,当您运行程序时,转到另一个终端并获取它的 PID (ps aux | grep myprog)。假设 PID 是 12345 然后你执行ls -la /proc/12345/fd 你会看到描述符 0 是一个管道(由 shell 完成)。所以你需要另一个标准输入......在 Linux 中你可以使用fopen("/dev/tty", "r"),但同样不能移植。

【讨论】:

    猜你喜欢
    • 2022-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 2021-06-11
    • 1970-01-01
    相关资源
    最近更新 更多