programing

셸의 파이프로 n개의 명령어를 연결?

lovejava 2023. 11. 5. 10:47

셸의 파이프로 n개의 명령어를 연결?

저는 C에 쉘을 구현하려고 합니다.간단한 execvp()로도 간단한 명령을 잘 실행할 수 있지만 요구 사항 중 하나는 다음과 같은 명령을 관리하는 것입니다. "ls -l | head | tail -4"는 'for' 루프와 stdin 및 stdout을 리디렉션하는 하나의 'pipe()' 문만 있는 것입니다.며칠이 지나니 길을 좀 잃었군요.

N = 단순 명령의 수(예에서 3개: ls, head, tail) 명령 = 다음과 같은 명령이 포함된 구조물 목록:

commands[0].argv[0]: ls
commands[0].argv[1]: -l
commands[1].argv[0]: head
commands[2].argv[0]: tail
commands[2].argv[1]: -4

그래서 포루프를 만들고 모든 명령을 파이프로 연결하기 위해 stdin과 stdout을 방향 전환하기 시작했습니다.왜 안 되는지 모르겠어요.

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

pipe(pipe);
if(fork()==0){  // CHILD

    close(pipe[0]);
    close(1);
    dup(pipe[1]);
    close(pipe[1]);

    execvp(commands[i].argv[0], &commands[i].argv[0]);
    perror("ERROR: ");
    exit(-1);

}else{      // FATHER

    close(pipe[1]);
    close(0);
    dup(pipe[0]);
    close(pipe[0]);

}
}

제가 만들고자 하는 것은 자식 프로세스의 '라인'입니다.

[ls -l] -------pipe----> [head] ---------pipe---> [tail -4]

이 모든 과정에는 루트(내 셸을 실행하는 과정)가 있습니다. 첫 번째 아버지도 셸 과정의 자녀입니다. 저는 이미 조금 지쳤습니다. 누가 여기서 저를 도와줄 수 있나요?

명령을 실행하는 사람이 아이들이어야 하는지도 잘 모르겠습니다.

고마워 얘들아!!

여기서 복잡한 것은 없습니다. 마지막 명령어는 원래 프로세스의 파일 설명자 1로 출력하고 첫 번째 명령어는 원래 프로세스 파일 설명자 0에서 읽어야 한다는 것을 명심하십시오.이전의 입력측을 따라 순서대로 프로세스를 생성하면 됩니다.pipe불러.

다음과 같은 유형이 있습니다.

#include <unistd.h>

struct command
{
  const char **argv;
};

단순하고 잘 정의된 의미론으로 도우미 기능을 만듭니다.

int
spawn_proc (int in, int out, struct command *cmd)
{
  pid_t pid;

  if ((pid = fork ()) == 0)
    {
      if (in != 0)
        {
          dup2 (in, 0);
          close (in);
        }

      if (out != 1)
        {
          dup2 (out, 1);
          close (out);
        }

      return execvp (cmd->argv [0], (char * const *)cmd->argv);
    }

  return pid;
}

그리고 주요 포크 루틴은 다음과 같습니다.

int
fork_pipes (int n, struct command *cmd)
{
  int i;
  pid_t pid;
  int in, fd [2];

  /* The first process should get its input from the original file descriptor 0.  */
  in = 0;

  /* Note the loop bound, we spawn here all, but the last stage of the pipeline.  */
  for (i = 0; i < n - 1; ++i)
    {
      pipe (fd);

      /* f [1] is the write end of the pipe, we carry `in` from the prev iteration.  */
      spawn_proc (in, fd [1], cmd + i);

      /* No need for the write end of the pipe, the child will write here.  */
      close (fd [1]);

      /* Keep the read end of the pipe, the next child will read from there.  */
      in = fd [0];
    }

  /* Last stage of the pipeline - set stdin be the read end of the previous pipe
     and output to the original file descriptor 1. */  
  if (in != 0)
    dup2 (in, 0);

  /* Execute the last stage with the current process. */
  return execvp (cmd [i].argv [0], (char * const *)cmd [i].argv);
}

그리고 작은 테스트:

int
main ()
{
  const char *ls[] = { "ls", "-l", 0 };
  const char *awk[] = { "awk", "{print $1}", 0 };
  const char *sort[] = { "sort", 0 };
  const char *uniq[] = { "uniq", 0 };

  struct command cmd [] = { {ls}, {awk}, {sort}, {uniq} };

  return fork_pipes (4, cmd);
}

효과가 있는 것 같습니다.:)

첫째, 파이프를 너무 일찍 닫고 있습니다.현재 프로세스에서 필요 없는 끝 부분만 닫고, 자식의 stdin/stdout을 닫아야 합니다.

두 번째로 이전 명령어의 fd를 기억해야 합니다.따라서 두 프로세스의 경우 다음과 같습니다.

int pipe[2];
pipe(pipe);
if ( fork() == 0 ) {
     /* Redirect output of process into pipe */
     close(stdout);
     close(pipe[0]);
     dup2( pipe[1], stdout );
     execvp(commands[0].argv[0], &commands[0].argv[0]);
} 
if ( fork() == 0 ) {
     /* Redirect input of process out of pipe */
     close(stdin);
     close(pipe[1]);
     dup2( pipe[0], stdin );
     execvp(commands[1].argv[0], &commands[1].argv[0]);
}
/* Main process */
close( pipe[0] );
close( pipe[1] );
waitpid();

여기에 오류 처리를 추가하고 n개의 프로세스를 시작할 수 있도록 n-1개의 파이프를 생성하는 것이 당신의 일입니다.첫 번째 fork() 블록의 코드는 프로세스 1..n-1의 해당 파이프에 대해 실행되어야 하고, 두 번째 fork() 블록의 코드는 프로세스 2..n에 대해 실행되어야 합니다.

언급URL : https://stackoverflow.com/questions/8082932/connecting-n-commands-with-pipes-in-a-shell