我试图让两个线程通过 linux 上的 C++ 中的管道进行通信(Ubuntu,12.04,3.8.13)。我只想将一个线程中的一个字符写入管道,然后让另一个线程读取并显示它。
我正在使用 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 中运行它也会给我非法指令。
有什么想法有什么问题吗?
任何帮助表示赞赏!