pthread create中传递的结构参数已损坏
我有一个名为command的结构,如下所示。枚举中的第一个值是AND_命令pthread create中传递的结构参数已损坏,c,multithreading,gnu,C,Multithreading,Gnu,我有一个名为command的结构,如下所示。枚举中的第一个值是AND_命令 struct command { enum command_type type; int status; char *input; char *output; union { struct command *command[2]; char **word; struct command *subshell_command; } u; }; 当我调用pthread\u
struct command
{
enum command_type type;
int status;
char *input;
char *output;
union
{
struct command *command[2];
char **word;
struct command *subshell_command;
} u;
};
当我调用pthread\u create时,我以命令的形式向它传递一个命令(转换为(void*))
我的线程接受这个(void*)命令,将其回滚(command),并尝试使用该结构
void execute_thread(void *c) {
command_t command = (command_t) c;
但是,当我传入一个结构以执行线程时,第一个值被清零。如果我的命令类型为SIMPLE,状态为-1,那么当它传入线程时,命令类型为,状态为0。但是,结构中的其他值均未更改。更奇怪的是,这种数据损坏是何时发生的。我能够在gdb中捕捉到这种现象:
445 command_t command = (command_t) c;
(gdb) p *((command_t) c)
$6 = {type = SIMPLE_COMMAND, status = -1, input = 0x605370 "abc", output = 0x605390 "def", u = {
command = {0x6052e0, 0x0}, word = 0x6052e0, subshell_command = 0x6052e0}}
(gdb) n
(gdb) p *((command_t) c)
$7 = {type = AND_COMMAND, status = 0, input = 0x605370 "abc", output = 0x605390 "def", u = {command = {
0x6052e0, 0x0}, word = 0x6052e0, subshell_command = 0x6052e0}}
在使用(command_t)c进行强制转换之前,c指向的结构似乎不会改变我完全被这种行为弄糊涂了。我不认为投射指针可以改变它指向的值。有人能指出,哈哈,这到底是怎么回事?我将非常感激
更奇怪的是,这种数据损坏是何时发生的。我能够在gdb中捕捉到这种现象:
445 command_t command = (command_t) c;
(gdb) p *((command_t) c)
$6 = {type = SIMPLE_COMMAND, status = -1, input = 0x605370 "abc", output = 0x605390 "def", u = {
command = {0x6052e0, 0x0}, word = 0x6052e0, subshell_command = 0x6052e0}}
(gdb) n
(gdb) p *((command_t) c)
$7 = {type = AND_COMMAND, status = 0, input = 0x605370 "abc", output = 0x605390 "def", u = {command = {
0x6052e0, 0x0}, word = 0x6052e0, subshell_command = 0x6052e0}}
这里的措辞让我相信这个问题不是确定性的;也就是说,有时它不会发生,或者它不会发生在您碰巧在问题中的gdb中捕获的那一刻
如果是这种情况(甚至可能不是),我怀疑您的问题在于您正在破坏分配给主线程中struct命令
的内存(或者创建execute\u thread()
thread的任何线程)。您没有向我们展示线程创建代码,但是如果您使用一个局部变量并将其地址传递给创建的线程,那么在第二个线程开始使用该局部变量之前,确保该局部变量的生存期不会过期可能会很棘手。您可能希望传入已在堆上分配的struct命令
:
struct command* thread_data = malloc(sizeof(struct command));
struct_command_init(thread_data);
pthread_create(/* ... */, thread_data);
// ...
在execute_command()
线程中:
void* execute_command(void* p)
{
struct command cmd = *(struct command*)p;
free(p);
// use cmd to get at the structure data passed in...
}
请记住,struct命令中的各种指针所引用的数据也需要对其生存期和所有权进行明确管理。Yup-这大约每周发生一次,速率逐渐向“float comparison not work”和“strcpy into char*myString cause segfault”攀升。