
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
char globe_buffer[100]
void *read_buffer_thread(void *arg) //这里先声明一下读缓存的线程,具体实现写在后面了
int main()
{
int res,i
pthread_t read_thread
for(i=0i<20i++)
globe_buffer[i]=i
printf("\nTest thread : write buffer finish\n")
sleep(3)\\这里的3秒是多余,可以不要。
res = pthread_create(&read_thread, NULL, read_buffer_thread, NULL)
if (res != 0)
{
printf("Read Thread creat Error!")
exit(0)
}
sleep(1)
printf("waiting for read thread to finish...\n")
res = pthread_join(read_thread, NULL)
if (res != 0)
{
printf("read thread join failed!\n")
exit(0)
}
printf("read thread test OK, have fun!! exit ByeBye\n")
return 0
}
void *read_buffer_thread(void *arg)
{
int i,x
printf("Read buffer thread read data : \n")
for(i=0i<20i++)
{
x=globe_buffer[i]
printf("%d ",x)
globe_buffer[i]=0//清空
}
printf("\nread over\n")
}
---------------------------------------------------------------------------------
以上程序编译:
gcc -D_REENTRANT test.c -o test.o –lpthread
运行这个程序:
$ ./test.o:
1.根据进程号进行查询:# pstree -p 进程号
# top -Hp 进程号
2.根据进程名字进行查询:
# pstree -p `ps -e | grep server | awk '{print $1}'`
# pstree -p `ps -e | grep server | awk '{print $1}'` | wc -l
这里利用了管道和命令替换,
关于命令替换,我也是今天才了解,就是说用``括起来的命令会优先执行,然后以其输出作为其他命令的参数,
上述就是用 ps -e | grep server | awk '{print $1}' 的输出(进程号),作为 pstree -p 的参数
管道和命令替换的区别是:
管道:管道符号"|"左边命令的输出作为右边命令的输入
命令替换:将命令替换符"``"中命令的输出作为其他命令相应位置的参数
第一个问题,不管是创建进程或者创建线程都不会阻塞,创建完毕马上返回不会等待子进程或者子线程的运行第二个问题
首先进程和线程是不一样的
多进程时,父进程如果先结束,那么子进程会被init进程接收成为init进程的子进程,接下来子进程接着运行,直到结束,init进程负责取得这些子进程的结束状态并释放进程资源。而如果是子进程先结束,那么父进程应当用wait或者waitpid去获取子进程的结束状态并释放进程资源,否则子进程会成为僵死进程,它占用的进程资源不会释放
多线程时,如果父线程或者说你讲的main结束时使用return或者exit或者处理完毕结束,那么整个进程都结束,其他子线程自然结束。如果main结束时使用的是pthread_exit那么只有父线程结束,子线程还在运行。同样对于子线程结束时如果调用了exit,那么整个进程包括父线程结束,如果调用了pthread_exit或者正常结束,那么只有子线程结束。
另外子线程结束时如果没有分离属性,其他线程应当使用pthread_join去获取线程结束状态并释放线程资源,如同进程里的wait和waitpid
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)