【发布时间】:2014-09-09 08:59:45
【问题描述】:
我在 ubuntu 和嵌入式 linux(我们的项目芯片)上运行以下代码。但是输出不同。为什么在嵌入式 linux 上运行时线程 errno 为 0?我怎样才能获得相同的输出? pthread_create() 函数可以设置errno吗?
此外,我使用了 fork() 函数而不是 pthread_create() 函数。在这种情况下,我用 ubuntu 得到了相同的输出。 例如:
if (fork())
print_message_function("foo");
ubuntu:
>>main errno: 2
>>thread errno: 2
嵌入式linux:
>>main errno: 2
>>thread errno: 0
使用 fork() 函数时嵌入 linux:
>>main errno: 2
>>thread errno: 2
#include <unistd.h> /* Symbolic Constants */
#include <sys/types.h> /* Primitive System Data Types */
#include <errno.h> /* Errors */
#include <stdio.h> /* Input/Output */
#include <stdlib.h> /* General Utilities */
#include <pthread.h> /* POSIX Threads */
#include <string.h> /* String handling */
#include <time.h>
typedef struct str_thdata
{
int thread_no;
char message[100];
} thdata;
int createError(char *str)
{
int retVal = 0;
if (NULL == fopen("YOK", "r"))
{
printf(">>%s errno: %d\n",str, errno);
retVal = -errno;
}
return retVal;
}
void print_message_function ( void *ptr )
{
int retVal;
thdata *data;
data = (thdata *) ptr;
retVal = createError("thread");
while(1)
;
pthread_exit(0);
}
int main()
{
int retVal = 0;
pthread_t thread1;
thdata data1;
data1.thread_no = 1;
strcpy(data1.message, "Hello!");
/*if (fork())
print_message_function("foo");
*/
pthread_create (&thread1, NULL, (void *) &print_message_function, (void *) &data1);
retVal = createError("main");
while(1)
{
}
pthread_join(thread1, NULL);
exit(0);
}
【问题讨论】:
-
你的
print_message_function有错误的返回类型,它应该返回void*,并且不要将你传递给pthread_create的函数转换为void*,它应该是void*(*)(void*)而不是void*,所以如果您只是修复返回类型,则无需强制转换它。
标签: multithreading thread-safety pthreads fork errno