share file descriptor between childs

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
#define BUFF_SIZE 256


#define CHILDS 4
#define DATAFILE "Client_Files.txt"

void worker(int n);
char str_buf[BUFF_SIZE];
FILE *datafile_fp;
int i;
    
char str_buf[BUFF_SIZE];
pid_t id[CHILDS];

int main() {

    if((datafile_fp = fopen( DATAFILE, "r"))== NULL)
    printf("grimi");



    
    for ( i = 0; i < CHILDS; i++ ){
        id = fork();
        if( id == 0 ){
            worker(i);
            exit(0);
        }
        else if ( id == -1 ){
            printf("fork error.\n");
            exit(0);
        }
        else {    
            //stuff;
        }

    }
    
}

void worker(int n) {
    fgets(str_buf, BUFF_SIZE, datafile_fp);
    printf("%c",str_buf[0]);
    
}

how can i share the file descriptor? each child have to read one line.. and they cant read the same one.. this works for the first line.. but then printf doest work...

thanks in advance..

The code you posted has a problem. But even if you solve that problem, there is another one. fork() dup()licates fd's from the parent but if you don't have some kind of synchronous read between the childs, you'll have unexpected results.

Do you really want to use multiple processes to read the same fd?

Try running this several times to see what I'm talking about:

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define CHILDS_N 5

void worker(int * fd)
{
        char buf[20];

        memset (buf, 0x0, sizeof (buf));
        read(*fd, buf, sizeof (buf)-1);
        printf ("%s\n", buf);

}


int
main ()
{
        pid_t childs[CHILDS_N];
        int fd;
        int i;
        fd = open ("Client_Files.txt", O_RDONLY);
        if (fd == -1)
                exit(1);


        for (i=0; i < CHILDS_N; i++)
        {
                childs = fork();
                if (childs == 0)
                {
                        worker(&fd);
                }
                else
                {
//                      printf ("parent: %d\n", getpid());
                }
        }
}

Hmm, i got that. But there is some way so i can read only a line in each child?

and can i use pthred_mutex for synchronization..?

I'd use flock(). Obtain lock, read n bytes, release lock, next child, etc...