programing

포크, exec, wait를 올바르게 사용하는 방법

minimums 2023. 10. 5. 21:25
반응형

포크, exec, wait를 올바르게 사용하는 방법

내가 쓰고 있는 셸은 사용자가 준 프로그램을 실행해야 합니다.제 프로그램의 아주 단축된 단순화된 버전입니다.

int main()
{
    pid_t pid = getpid(); // this is the parents pid

    char *user_input = NULL;
    size_t line_sz = 0;
    ssize_t  line_ct = 0; 

    line_ct = getline(&user_input, &line_sz, stdin); //so get user input, store in user_input

    for (;;)
    {
        pid_t child_pid = fork(); //fork a duplicate process

        pid_t child_ppid = getppid(); //get the child's parent pid

        if (child_ppid == pid) //if the current process is a child of the main process
        {
            exec(); //here I need to execute whatever program was given to user_input
            exit(1); //making sure to avoid fork bomb
        }

        wait(); //so if it's the parent process we need to wait for the child process to finish, right?

    }
}
  1. 새 프로세스를 포크하고 하위 프로세스인지 확인했습니다.
  2. 제가 하려는 일에 어떤 간부를 이용할 수 있을까요?가장 간단한 방법은?
  3. 제 주장은 무엇입니까?제가 보고 있는 문서는 별로 도움이 되지 않습니다.

사용자가 ls, ps, pwd와 같은 것을 입력할 수 있다고 가정합니다.

감사해요.

편집:

const char* hold = strdup(input_line);
char* argv[2]; 

argv[0] = input_line;
argv[1] = NULL;

char* envp[1];
envp[0] = NULL;

execve(hold, argv, envp);

다음은 간단하고 읽을 수 있는 솔루션입니다.

pid_t parent = getpid();
pid_t pid = fork();

if (pid == -1)
{
    // error, failed to fork()
} 
else if (pid > 0)
{
    int status;
    waitpid(pid, &status, 0);
}
else 
{
    // we are the child
    execve(...);
    _exit(EXIT_FAILURE);   // exec never returns
}

어린이는 저장된 값을 사용할 수 있습니다.parent부모의 PID를 알아야 하는 경우(이 예에서는 모르지만).부모는 아이가 끝날 때까지 기다리기만 합니다.효과적으로, 아이는 부모 안에서 "동기적으로" 뛰어다니며, 평행성이 없습니다.부모가 조회할 수 있습니다.status어린이가 어떤 방식으로 빠져나갔는지 확인합니다(성공했는지, 실패했는지, 또는 신호와 함께).

언급URL : https://stackoverflow.com/questions/19099663/how-to-correctly-use-fork-exec-wait

반응형