簡體   English   中英

孩子內部的值修改不會更新

[英]Value modification inside child doesn't update

我試圖在 fork(); 時修改子進程內的 int; 但我不能讓程序多次更新它,我的想法是添加一個計數器,顯示到屏幕上,顯示有多少 bg 在哪里(何時 & 位於行尾),但我不知道為什么會這樣不工作。 現在我正在嘗試這個但它也不起作用,也許我應該修改父進程中的值? 這是代碼:

void execute(char **tokens, int token_Size, int *blk){
pid_t pid, wpid;
int status;
int result;

int flag;

int isPipe;
int output;
int input;

int isAmper;
pid = fork();
if (pid == -1)
{
    perror("Fork:");
    exit(1);
}
else if (pid == 0)
{
    isAmper = needs_amper(tokens, token_Size);
    output = needs_out_redir(tokens, token_Size);
    input = needs_in_redir(tokens, token_Size);
    isPipe = needs_pipe(tokens, token_Size);
    static int bloq = 1;

    if (isAmper != -1)
    {
        *blk +=1;
        printf("[%d] %d \n", *blk, getppid()); //-> [blk] is the job number asigned to the job
        tokens[isAmper] = NULL;
    }

    if (strcmp(tokens[0], "echo") == 0)
    {
        for (int i = 1; tokens[i]; i++)
        {
            printf("%s ", tokens[i]);
        }
    }

    flag = 0;

    if (output != -1)
    {
        redirect_output(tokens, output);
        tokens[output] = NULL;
        flag = 1;
    }

    if (input != -1)
    {
        redirect_input(tokens, input);
        tokens[input] = NULL;
        flag = 1;
    }

    if (isPipe != -1)
    {
        create_pipe(tokens, output, input, isPipe);
    }

    if (flag || isPipe == -1)
    {
        execvp(tokens[0], tokens);
        perror("Unkown Command:");
        exit(1);
    }

    //  exit(0);
}
else // Main (parent) process after fork succeeds
{
    
    while ((wpid = wait(&status)) > 0)
        ; // this way, the father waits for all the child processes

    result = waitpid(pid, &status, 0);
    if (result == 1) //If the process terminated correctly, result returns 0.
    {
        printf("The child process terminated with an error!.\n");
    }
}}

我正在嘗試修改傳遞給執行函數的blk值,我也嘗試使用內部值,但也不起作用。 讓我的自我更清晰。 我希望當我在我的自定義 shell 中輸入一些帶有“&”的東西時,它會返回如下內容:

ivo@ivo-Surface-Pro-6:/home/ivo/Documents/SO1/soi-myshell-Ivoo25$ echo hola &

[1] 10853

你好

下次我用 & 結尾輸入內容時..

[2] 10853

main.c main.o Makefile myshell myShell.c myShell.h myShell.o README.md

我認為我嘗試做的事情無法完成,因為每次執行的 pid 都是相同的,也許是這樣?

我設法得到它,我添加了相同的功能

needs_amper(tokens, token_Size)

但是在子進程之外,在 if 函數內部的 fork 之前,它返回一個大於 0 的值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM