【问题标题】:How to use execlp()?如何使用 execlp()?
【发布时间】:2023-03-13 00:00:01
【问题描述】:

如何使第二个execlp("sort","sort,",(char *)0) 输出到显示器?

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "errno.h"

int main()
{
    int parprocID = getppid();//parent process id
    int c1Toc2[2];
    int c2Toc1[2];                            
    pipe(c1Toc2);//pipe 1, to child 2
    pipe(c2Toc1);//pipe 2, to child 1

    int cpid = 0;//child 1 pid
    int cpid2 = 0;//child 2 pid

    int child1,child2;//Child variable

    printf("Parent Process id is: %d.\n\n", parprocID);//parent pid introduction.

    child1 = fork();//creation of child 1
    if(child1 == 0)
    {
        cpid = getpid();
        printf("Child 1 created by process: %d has an id of %d.\n\n", parprocID, getpid());

        dup2(c1Toc2[1], STDOUT_FILENO);//redirect from stdout to pipe

        execlp("ls", "ls","-al","/bin", (char *)0);             

        exit(0);
    }
    else
    {
        child2=fork();  //creation of child 2   
        if(child2 == 0)
        {
            cpid2 = getpid();
            printf("Child 2 created by process: %d has an id of %d.\n", parprocID, getpid());

            dup2(c1Toc2[0], STDIN_FILENO);

            execlp("sort", "sort", (char *)0);
            exit(0);    
            close(c1Toc2[0]);
            close(c1Toc2[1]);   
        }
    }

    sleep(3);
    printf("PARENT: PROCESS waiting on children to complete\n");

    wait(NULL);
    wait(NULL);

    printf("Final print statement before exit\n");
    exit(0);
}

子 1 具有 execlps 系统调用,因此子 1 执行 ls 程序。 dup2 将输出重定向到管道。 我认为孩子 2 execlp 对 ls 进行排序,但代码只是挂起,我不确定我是否做得对,我期待孩子 2 显示孩子 1 重定向的内容。接下来会发生什么或我哪里出错了?

【问题讨论】:

标签: c


【解决方案1】:

父进程和子进程 2(排序)也打开了管道的写入端,因此排序正在等待其标准输入上的更多输入:sleep(3); 之前和 execlp("sort", "sort", (char *)0); 之前的 close(c1Toc2[1]); 必须是已添加。

【讨论】:

    猜你喜欢
    • 2015-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多