Parent process and child process

I am trying to write a program in which the parent process will take main () arguments and send characters to them one by one for the child process through the channel (one call to write for each character). The child process will read the characters sent to it by the parent process and print the number of characters received from the parent. A child process should not use the main () arguments in any way. The child should return normally and not have a parent killing the child.

How to count arguments? Am I sending arguments one at a time and am I reaping a child?

#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define size = 100;

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

    int i, count =0;
    int c;

    int     fdest[2];          // for pipe
    pid_t   pid;              //process IDs
    char    buffer[BUFSIZ];



    if (pipe(fdest) < 0)          /* attempt to create pipe */
        perror( "pipe" );

    if ((pid = fork()) < 0)  /* attempt to create child / parent process */

    {
        perror( "fork" );
    } 


    /* parent process */
    else if (pid > 0) { 

        close(fdest[0]);
        for (i=1; i < argc; ++i) 
        {
            for (c=0; c < strlen(argv[i]); ++c) {
                write(fdest[1], &argv[i][c], 1);
            }
        }

        close(fdest[1]);         
        wait(NULL);             
        exit(0);

    } else {   

        /* child Process */
        close(fdest[1]);

        while (read(fdest[0], &buffer, 1) > 0)
        {
            count++;
        }


        printf("\nchild: counted %d characters\n", count);

    }
    wait(NULL);
    exit(0);

}
+3
source share
1 answer

() ; , . "" (0); 'return (0);'. 'exit (0);' .

"#define size = 100;" , , "=" ( - - ). "#define size 100" "enum { size = 100 };". " ", "enum { size = 100 };.

, BUFSIZ ( 512 ).

, "for (c = 0; c < strlen(argv[c]); c++)", . :

for (const char *str = argv[i]; *str != '\0'; str++)
    write(fdest, str, 1);

for (c = 0, len = strlen(argv[i]); c < len; c++)
      write(fdest[1], &argv[i][c], 1);

- .

, , . , . , ?

+2

Source: https://habr.com/ru/post/1736824/


All Articles