gpt4 book ai didi

c++ - 在 Linux 上的 C++ 中的两个线程之间使用管道的错误/意外行为

转载 作者:太空宇宙 更新时间:2023-11-04 11:18:49 24 4
gpt4 key购买 nike

我试图让两个线程在 Linux(Ubuntu、12.04、3.8.13)上通过 C++ 中的管道进行通信。我只想从一个线程向管道写入一个字符,让另一个线程读取它并显示它。

我正在使用 clone() 函数来创建线程。这与一些作业有关,所以我不能使用 pthreads 或其他东西。

程序:

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <cstdio>
#include <climits>
#include <fstream>
#include <cmath>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <sched.h>

#include <fcntl.h>

using namespace std;

int p[2];//pipe

void read_pipe()
{
int c;
char charac[2];
read(p[0],charac,sizeof(charac));
//usleep(1000);
cerr<<"Read from pipe: "<<charac<<endl;
}

void write_pipe ()
{

write(p[1],"a",sizeof("a"));
cerr<<"Wrote to pipe: "<<"a"<<endl;
}

int thread1(void*)
{
close(p[0]);
write_pipe();
_exit(0);
}

int thread2(void*)
{
close (p[1]);
read_pipe();
_exit(0);
}


int main()
{
pipe(p);

char *stack_thread1=(char*)malloc(16384);
stack_thread1 +=16383;//stack grows downward -- gives seg fault otherwise

char *stack_thread2=(char*)malloc(16384);
stack_thread2 +=16383;//stack grows downward -- gives seg fault otherwise

int64_t elapsed_ns=0;

//create thread1
int tpid1=clone(thread1, (void*)stack_thread1, CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_VM, NULL);
cerr<<"\nThread1 created\n";

//create thread2
int tpid2=clone(thread2, (void*)stack_thread2, CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_VM, NULL);
cerr<<"\nThread2 created\n";

waitpid(tpid1,NULL,__WCLONE);//wait for clones to finish
waitpid(tpid2,NULL,__WCLONE);
usleep(5000);//make sure clones finished
cout<<"\nMain thread after sleep\n";


return 0;

}

输出很奇怪,每次都不一样,例如:

Thread1 created

Thread2 created
Read from pipe:

Main thread after sleep

有时它会给我错误:非法指令。在 gdb 中运行它也会给我非法指令。

有什么问题吗?

感谢任何帮助!

最佳答案

如果您传递了CLONE_FILES 标志,您将无法关闭您的管道文件,因为两个线程共享同一组文件描述符。从一个线程关闭它也会为另一个线程关闭它。

关于c++ - 在 Linux 上的 C++ 中的两个线程之间使用管道的错误/意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19527777/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com