【问题标题】:Running a program with semaphores使用信号量运行程序
【发布时间】:2019-05-25 20:14:36
【问题描述】:

我有这个来自官方 geeks4geeks 网站的程序,它在 2 个线程之间使用信号量:

// C program to demonstrate working of Semaphores 
#include <stdio.h> 
#include <pthread.h> 
#include <semaphore.h> 
#include <unistd.h> 

sem_t mutex; 

void* thread(void* arg) 
{ 
    //wait 
    sem_wait(&mutex); 
    printf("\nEntered..\n"); 

    //critical section 
    sleep(4); 

    //signal 
    printf("\nJust Exiting...\n"); 
    sem_post(&mutex); 
} 


int main() 
{ 
    sem_init(&mutex, 0, 1); 
    pthread_t t1,t2; 
    pthread_create(&t1,NULL,thread,NULL); 
    sleep(2); 
    pthread_create(&t2,NULL,thread,NULL); 
    pthread_join(t1,NULL); 
    pthread_join(t2,NULL); 
    sem_destroy(&mutex); 
    return 0; 
} 

根据这个站点运行它会打印这个结果:

Entered..

Just Exiting...

Entered..

Just Exiting...

在我的 ubuntu linux 计算机中,我使用 gcc main.c -lpthread -lrt 编译它,它编译成功,但之后尝试使用 ./main.c 运行它会给我以下错误:

./main.c: line 8: sem_t: command not found
./main.c: line 10: syntax error near unexpected token `('
./main.c: line 10: `void* thread(void* arg)'

我应该用不同的命令运行它还是我在这里遗漏了什么?请帮忙。

【问题讨论】:

    标签: c operating-system


    【解决方案1】:

    编译代码后,您应该有一个名为a.out 的文件,它是可执行文件。使用./a.out 运行它。 您可以使用选项-o &lt;name&gt; 为可执行文件指定另一个名称。无论如何,请查看man gcc 了解更多信息。 编译代码的完整命令是

    gcc main.c -o main -lpthread -lrt
    

    【讨论】:

      【解决方案2】:

      ./main.c 不应该是你运行的命令。

      编译后,您应该得到一个可以运行的可执行文件,而不是源文件。

      【讨论】:

      • 用 gcc main.c -o main 编译它会给我多个错误,但是用 gcc main.c -lpthread -lrt 什么也没有发生(编译成功?)我必须在终端中输入一个新命令.这必须是哪个命令?
      • @leonardoystapor 在您刚刚编译的文件夹中创建ls -alrth:最后修改/创建的文件可能是您必须启动的文件。
      猜你喜欢
      • 1970-01-01
      • 2013-03-13
      • 1970-01-01
      • 1970-01-01
      • 2015-01-05
      • 2013-08-16
      • 1970-01-01
      • 2015-04-13
      • 1970-01-01
      相关资源
      最近更新 更多