我正在尝试编写一个程序,当通过命令行运行并给出 2 个数字时,一个用于线程数,一个用于要测试的整数,以显示该 int 的总和和阶乘积。但是,当我编译并运行它时,命令行显示权限被拒绝。即使我更改了所有读写权限。我的代码有问题吗?
我使用 gcc -oterm -lpthread filename.c 进行编译,然后使用 ./a.out 10 5 运行它。这是不正确的吗?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int sum,ms;
void *getSum(void *param);
void *factorial(void *para);
void * getSum(void *id)
{
int x, upper = (int)id;
sum = 0;
for(x = 1; x <= upper; x++)
sum += x;
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
if (argc != 3)
{
printf("Command line arguments missing. Exiting\n");
exit(-1);
}
int threads = atoi(argv[1]);
int stopValue = atoi(argv[2]);
int sums = 0;
int mults = 1;
pthread_t* tid = (pthread_t*)calloc(threads + 1, sizeof(pthread_t));
int status, num, x;
for(x = 0; x < threads; x++)
{
if (x % 2 == 0 || x == 0)
status = pthread_create(&tid[x], NULL, getSum, (void*)(int) x);
else
status = pthread_create(&tid[x], NULL, factorial, (void*)(int) x);
if(status != 0 )
{
printf("error creating thread\n");
exit(-1);
}
}
for (x = 0; x < threads; x++)
pthread_join(tid[x], NULL);
printf("The sum value is %d\n", sums);
printf("The mult value is %d\n", mults);
free(tid);
pthread_exit(NULL);
return 0;
}
void *factorial(void *para)
{
int i, upper = atoi(para);
ms = 1;
for(i = 2; i <= upper; i++)
{
ms = (ms * i);
}
pthread_exit(0);
}
最佳答案
I compile using gcc -oterm -lpthread filename.c and then run it using ./a.out 10 5 for example. is this incorrect?
是的,因为您指定了 -oterm
,编译后的可执行文件将被命名为 term
。所以你需要使用 ./term 10 5
而不是 ./a.out 10 5
对于使用 pthread 的编译代码,您应该使用 -pthread
标志而不是仅仅与 pthread 库链接,并且至少启用一些警告。所以用
gcc -Wall -o term -pthread filename.c
关于c - 在尝试运行 C pthread 程序的命令行中出现权限被拒绝错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21359189/