c - 将 UNIX 管道与 C 一起使用

标签 c unix

我需要创建 6 个线程来同时执行任务(递增/递减数字),直到整数变为 0。我应该只使用 UNIX 命令(具体来说是管道),但我无法得到我的了解管道如何工作,或者如何实现这个程序。

这个整数可以存储在文本文件中。

如果有人能解释如何实现这个程序,我将非常感激

最佳答案

这本书是对的,管道可以用来保护关键部分,尽管如何做到这一点并不明显。

int *make_pipe_semaphore(int initial_count)
{
   int *ptr = malloc(2 * sizeof(int));
   if (pipe(ptr)) {
       free(ptr);
       return NULL;
   }
   while (initial_count--) 
       pipe_release(ptr);
   return ptr;
}

void free_pipe_semaphore(int *sem)
{
    close(sem[0]);
    close(sem[1]);
    free(sem);
}

void pipe_wait(int *sem)
{
    char x;
    read(sem[0], &x, 1);
}

void pipe_release(int *sem)
{
   char x;
    write(sem[1], &x, 1);
}

信号量中的最大可用资源因操作系统而异,但通常至少为 4096。这对于保护初始值和最大值均为 1 的关键部分来说并不重要。

用法:

/* Initialization section */
int *sem = make_pipe_semaphore(1);



/* critical worker */
{
    pipe_wait(sem);
    /* do work */

    /* end critical section */
    pipe_release(sem);
}

关于c - 将 UNIX 管道与 C 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3929365/

相关文章:

bash - 如何在 Unix Shell 中遍历字符串中的每个字母

c - omp_set_num_threads(1) 比没有 openmp 慢的原因

c - typedef 枚举相关错误

c++ - 低功耗蓝牙 : setting characteristic to byte array sends wrong values

linux - 终端 - 删除所有不包含 .mp3 文件的文件夹

unix - 查找命令 : search with created time

android - C 源代码不会为 ARM 架构编译

c - 如何为预处理器创建变量值 channel ?

c - 退格进入 C char*

linux - 为什么 crontab 成功运行了我的 shell 脚本,但无法启动我的二进制文件程序?