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

标签 c++ linux multithreading pipe named-pipes

我试图让两个线程在 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/

相关文章:

linux - 搜索票务系统、建议

ios - NSOperationQueue的多个分配使我的应用程序崩溃

c++ - 为什么我在使用++ 时出现段错误,但在使用 '1 +' 时却没有?

c++ - 从 boost::chrono::steady_clock::now() 获得双倍

regex - 在 Linux 中附加到带有 "sed"的文本文件

java - Executor服务线程,一些本地连接对象

c++ - 使用 cudaSetDeviceFlags 的正确位置?

c++ - 删除从 i 到行尾的字符串的一部分

c++ - 传递函数对象时编译器错误

linux - cron 作业的服务器使用情况是什么?