使用POPEN之间的管道之间的通信

发布于 2025-02-09 12:15:18 字数 1099 浏览 0 评论 0原文

我想:

  1. 最终通过使用FGETC和FEOF来优化此代码。
  2. 知道是否有另一个代码做

我代码的基本思想的做法是创建一个计数器,每次调用popen。计数器一旦达到一定值,在这种情况下,它将与状态之前的所有过程通信,然后关闭

    int main (int argc, char* argv[]) {
        
        int counter = atoi(argv[1]);
    
        if (counter == 5) {
            printf("I am number 5, I Quit !\n");
            fflush(stdout);
            sleep(1);
            return 0;
        }
    
        char new_command [20];
        snprintf(new_command, sizeof(new_command), "%s %d", argv[0], counter+1);
        FILE* fp = popen(new_command, "r");
    
        const struct timespec chock = {0,10000};
    
        char letter;
        char keep_on = 'y';
        while(keep_on == 'y') {
            while(fread(&letter, sizeof(letter), 1, fp) != 0) {
                printf("%c", letter);
                if (letter == '\n') {
                    keep_on = 'n';
                }
    
            }
            fflush(stdout);
            nanosleep(&chock, NULL);
        }
    
        printf("%d: Finished\n", counter);

    
        return 0;
    }

i want to :

  1. optimize this code eventually by using fgetc and feof.
  2. know if there is another do what this code do

The basic idea of ​​my code is to create a counter that increments with each call to popen. As soon as the counter reaches a certain value, in this case 5, it communicates to all the processes before its state and then closes

    int main (int argc, char* argv[]) {
        
        int counter = atoi(argv[1]);
    
        if (counter == 5) {
            printf("I am number 5, I Quit !\n");
            fflush(stdout);
            sleep(1);
            return 0;
        }
    
        char new_command [20];
        snprintf(new_command, sizeof(new_command), "%s %d", argv[0], counter+1);
        FILE* fp = popen(new_command, "r");
    
        const struct timespec chock = {0,10000};
    
        char letter;
        char keep_on = 'y';
        while(keep_on == 'y') {
            while(fread(&letter, sizeof(letter), 1, fp) != 0) {
                printf("%c", letter);
                if (letter == '\n') {
                    keep_on = 'n';
                }
    
            }
            fflush(stdout);
            nanosleep(&chock, NULL);
        }
    
        printf("%d: Finished\n", counter);

    
        return 0;
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文