如何在C语言中正常运行这两个进程?

huangapple go评论93阅读模式
英文:

how can i run these two proceses normally in c language?

问题

这段代码运行正常,但消费者进程不工作,我尝试获取producer_pid的值并检查发生了什么情况,但当我写下printf("%d\n", producer_pid)时,不加\n时它会输出两个值,加上\n时则只输出一个值。我对计算机编程一窍不通,正在自学,如果问题问得不好,我很抱歉。

我认为生产者进程没有结束,有什么能帮助我的想法吗?

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#define BUFFER_SIZE 2

int buffer[BUFFER_SIZE];
int sayac = 0;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void produce(int item) {
    buffer[sayac] = item;
    sayac++;
}

int consume() {
    int item = buffer[sayac - 1];
    sayac--;
    return item;
}

void *producer_thread(void *arg) {
    int *pipe_fd = (int *)arg;

    for (int i = 1; i <= 10; i++) {
        pthread_mutex_lock(&mutex);
        while (sayac == BUFFER_SIZE) {
            pthread_mutex_unlock(&mutex);
            usleep(100000);  // Wait for a short time and release the loop
            pthread_mutex_lock(&mutex);
        }

        produce(i);
        printf("Producer: %d produced.\n", i);

        write(pipe_fd[1], &i, sizeof(i));

        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
    close(pipe_fd[1]);
    return NULL;
}

void *consumer_thread(void *arg) {
    int *pipe_fd = (int *)arg;

    for (int i = 1; i <= 10; i++) {
        pthread_mutex_lock(&mutex);
        while (sayac == 0) {
            pthread_mutex_unlock(&mutex);
            usleep(100000);  // Wait for a short time and release the loop
            pthread_mutex_lock(&mutex);
        }

        int item = consume();
        printf("Consumer: %d consumed.\n", item);

        int received_data;
        read(pipe_fd[0], &received_data, sizeof(received_data));

        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
    close(pipe_fd[0]);
    return NULL;
}

int main() {
    int pipe_fd[2];
    if (pipe(pipe_fd) == -1) {
        perror("Pipe could not be created");
        return 1;
    }

    pid_t producer_pid = fork();
    printf("%d ---------------", producer_pid);

    if (producer_pid == 0) {
        // Child producer process code
        close(pipe_fd[0]); // Close the reading end
        producer_thread((void *)pipe_fd);
        exit(0);
    } else if (producer_pid > 0) {
        pid_t consumer_pid = fork();

        if (consumer_pid == 0) {
            // Child consumer process code
            close(pipe_fd[1]); // Close the writing end
            consumer_thread((void *)pipe_fd);
            exit(0);
        } else if (consumer_pid > 0) {
            // Main process code
            close(pipe_fd[0]); // Close the reading end
            close(pipe_fd[1]); // Close the writing end

            wait(NULL);
            wait(NULL);

            printf("Main process completed.\n");
        } else {
            fprintf(stderr, "Consumer process could not be created.\n");
            return 1;
        }
    } else {
        fprintf(stderr, "Producer process could not be created.\n");
        return 1;
    }

    return 0;
}
英文:

this code works fine but consumer process does not work, i tried to get producer_pid value and check what is going on but when i write the printf("%d\n",producer_pid) it gives two values when do not put \n it gives one value. i am new to all computer programming i am educating myself, if the question is so bad i am sorry

i think producer process is not ending any idea that could help me?

#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;pthread.h&gt;
#include &lt;unistd.h&gt;
#include &lt;sys/types.h&gt;
#include &lt;sys/wait.h&gt;
#define BUFFER_SIZE 2
int buffer[BUFFER_SIZE];
int sayac = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void produce(int item) {
buffer[sayac] = item;
sayac++;
}
int consume() {
int item = buffer[sayac - 1];
sayac--;
return item;
}
void *producer_thread(void *arg) {
int *pipe_fd = (int *)arg;
for (int i = 1; i &lt;= 10; i++) {
pthread_mutex_lock(&amp;mutex);
while (sayac == BUFFER_SIZE) {
pthread_mutex_unlock(&amp;mutex);
usleep(100000);  // Kısa bir s&#252;re bekleyerek d&#246;ng&#252;y&#252; serbest bırak
pthread_mutex_lock(&amp;mutex);
}
produce(i);
printf(&quot;&#220;retici: %d &#252;retildi.\n&quot;, i);
write(pipe_fd[1], &amp;i, sizeof(i));
pthread_mutex_unlock(&amp;mutex);
sleep(1);
}
close(pipe_fd[1]);
return NULL;
}
void *consumer_thread(void *arg) {
int *pipe_fd = (int *)arg;
for (int i = 1; i &lt;= 10; i++) {
pthread_mutex_lock(&amp;mutex);
while (sayac == 0) {
pthread_mutex_unlock(&amp;mutex);
usleep(100000);  // Kısa bir s&#252;re bekleyerek d&#246;ng&#252;y&#252; serbest bırak
pthread_mutex_lock(&amp;mutex);
}
int item = consume();
printf(&quot;T&#252;ketici: %d t&#252;ketildi.\n&quot;, item);
int received_data;
read(pipe_fd[0], &amp;received_data, sizeof(received_data));
pthread_mutex_unlock(&amp;mutex);
sleep(1);
}
close(pipe_fd[0]);
return NULL;
}
int main() {
int pipe_fd[2];
if (pipe(pipe_fd) == -1) {
perror(&quot;Pipe oluşturulamadı&quot;);
return 1;
}
pid_t producer_pid = fork();
printf(&quot;%d ---------------&quot;,producer_pid);
if (producer_pid == 0) {
// Yavru &#252;retici işlem kodu
close(pipe_fd[0]); // Okuma tarafını kapat
producer_thread((void *)pipe_fd);
exit(0);
} else if (producer_pid &gt; 0) {
pid_t consumer_pid = fork();
if (consumer_pid == 0) {
// Yavru t&#252;ketici işlem kodu
close(pipe_fd[1]); // Yazma tarafını kapat
consumer_thread((void *)pipe_fd);
exit(0);
} else if (consumer_pid &gt; 0) {
// Ana işlem kodu
close(pipe_fd[0]); // Okuma tarafını kapat
close(pipe_fd[1]); // Yazma tarafını kapat
wait(NULL);
wait(NULL);
printf(&quot;Ana işlem tamamlandı.\n&quot;);
} else {
fprintf(stderr, &quot;T&#252;ketici işlem oluşturulamadı.\n&quot;);
return 1;
}
} else {
fprintf(stderr, &quot;&#220;retici işlem oluşturulamadı.\n&quot;);
return 1;
}
return 0;
}

答案1

得分: 1

主要问题在于您正在打开一个pthread互斥锁以在使用fork()打开的进程之间同步。

pthread_mutex的设计是用于线程之间的同步,它无法在使用fork创建的进程之间进行同步,因为这些进程将具有不同的内存空间。

对于您的实现,甚至没有必要使用pthread_mutex。write()和read()是阻塞的,所以您可以通过使用pipe来使这两个进程同步。

另外,当您使用printf()时,有时操作系统会等待而不打印所有的日志。使用fflush()来查看所有的日志。

英文:

the main problem here is that you're opening a pthread mutex to sync between processes opened using fork().

pthread_mutex, as its name would suggest, is designed to sync between threads.
It will not be able to sync between processes created using fork since the processes will have a different memory space.

For your implementation, there isn't much of a point to even use pthread_mutex. write() and read() are blocking, so you can have both processes sync by using the pipe.

On a different subject, when you use printf(), sometimes the OS will wait and not print all of the log. use fflush() to see all your logs.

huangapple
  • 本文由 发表于 2023年8月9日 17:04:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76866164-2.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定