简体   繁体   中英

Problems using the fork function linux

I'm trying to achieve the following: I read nr words from input text file and for each word I want to start a child process to modify the word and return it in an output text file. The output fluctuates, sometimes I get the words messed up ( apple banana into appbananale) and sometimes the output file is 20kb and it freezes the text editor.

int main(int argc, char **argv){

    int in, out, i, nr, k, j;
    char buffer[100];

    in = open(argv[1], O_RDONLY);
    if (in == -1){
        perror(NULL);
        return errno;
    }
    out = open(argv[2], O_WRONLY | O_CREAT, 0666);
    if (out == -1){
        perror(NULL);
        return errno;
    }
    if (read(in, buffer, 100) == -1){
        perror(NULL);
        return errno;
    }
    nr = 5;
    k=0;
    srand(time(NULL));
    char v[20];
    int l;
    j=0;
    pid_t pid;
    for (i=1;i<sizeof(buffer);i++){
        if (k == nr) break;

        if (buffer[i]=='\n'){
            k++;
            pid = fork();
            if (pid < 0)
                return errno;
            if (pid == 0){
                //for (l=0;l<j;l++)
                write (out, v, j);
                return 0;
            }
            j=0;
        }
        else{
            j++;
            v[j-1]=buffer[i];   
        }

    }


    return 0;
}


Each of your child processes is writing to the same output stream, and they're all running concurrently, so their outputs are mixed together.

Instead of writing one character at a time, write the whole line. Calls to write() to a local POSIX-conforming filesystem are atomic, so you won't get data mixed between each process.

So change the loop:

for (l=0;l<j;l++)
    write (out, v+l, 1);

to

write(out, v, j);

See Atomicity of `write(2)` to a local filesystem for various caveats about this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM