Simon
Simon

Reputation: 95

C : printf() not thread safe with flockfile()

I need to print some messages on screen, and my program is multiprocess and multithread. I used flockfile(), flock() and mutex, but some messages are overlapped. I did also a basic test program, and the result is the same. Why i cannot synchronize the output?

void my_printf() {
    int i;
    for (i=0; i<20000; ++i) {
        flockfile(stdout);
        printf("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\n");
        fflush(stdout);
        funlockfile(stdout);
    }
}


int main()
{
    fork();
    fork();
    fork();
    my_printf();
    exit(0);
}

EDIT

@Joachim Pileborg I have tried to use sem_t semaphores, but i had the same result...strings are overlapped.

struct my_struct {
    sem_t *t;
};

struct my_struct *create_shared_memory(void)
{
    struct my_struct *str;
    key_t key;
    int fd;

    key = ftok("/", '5');
    fd = shmget(key, sizeof(struct my_struct), IPC_CREAT|0666);
    str = shmat(fd, NULL, 0);
    str->t = sem_open("/my_sem", O_CREAT|O_EXCL, 0644, 1);

    return str;
}

void my_printf(struct my_struct *str){
    int i;
    for (i=0; i<20000; ++i) {
        sem_wait(str->t);
        printf("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\n");
        sem_post(str->t);
        fflush(stdout);
    }
}


int main()
{
    struct my_struct *my = create_shared_memory();
    fork();
    fork();
    my_printf(my);

    exit(0);
}

Upvotes: 0

Views: 1177

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409196

The flockfile function is for locking for other threads, not processes. If you want inter-process locking look at e.g. POSIX semaphores, especially the named ones.

Upvotes: 4

Related Questions