C程序如何同时做2件事?

binb 2000-06-11 12:03:00
加精
UNIX C编程有这样一个问题:某程序运行后,要同时做两件事
待其中一件事完毕,另一件事(放音乐)终止,
好象通过多线程可完成这个问题,但不知如何做?
最好有例子程序!
谢谢
...全文
460 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
hem 2001-05-18
  • 打赏
  • 举报
回复
参考
halfdream 2000-06-12
  • 打赏
  • 举报
回复
在UNIX类的操作系统上用多进程很方便。
用fork() 产生子进程,然后通过判断pid 的值知道是哪个进程。

呵呵,听了你提的第二个问题,觉得
你确实该看看书。 就算一般的操作系统书上都提过这些的。
fjp 2000-06-12
  • 打赏
  • 举报
回复
提供一个例子,供你参考.

#include <stdio.h>
#include <signal.h>
void sig(int signo)
{
//子进程接到信号后做一些终止前的善后工作
exit(0) ;
}

void ChildFunc()
{
//播放音乐等后台进程
}

void ParentFunc()
{
//父进程工作函数
}

////////////////////////////////////////////////////////////////////

main()
{
int pid ;

switch((pid = fork()))
{
case 0 : //child process
if(signal(SIGUSR1, sig) == SIG_ERR)
{
perror("signal") ;
exit(-1) ;
}
ChildFunc() ;
break ;
case -1 :
perror("fork") ;
break ;
default : //parent process
ParentFunc() ;
kill(pid, SIGUSR1) ; //工作完后发信号给子进程要求其终止
wait(0) ; //等待子进程终止
break ;
} //switch
printf("program over!\n") ;
}

solar 2000-06-12
  • 打赏
  • 举报
回复
使用线程的例子
// do2things.c
// build: cc -o do2things -Wall do2things.c -lpthread
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>

static int ok_to_exit=0;

// function for thread
void * thread_func(void *arg)
{
char *ret_val=(char*)malloc(128);
while(!ok_to_exit){
fprintf(stdout,"I'm working!\n");
}

sprintf(ret_val,"ok,i'll exit");
pthread_exit(ret_val);

return ret_val; // only to avoid warning message at compile time
}

int main(int argc, char* argv[])
{
int i=0;
char *ret_buf;
pthread_t ptid;

// set up the thread to play music in background
pthread_create(&ptid, NULL,thread_func,NULL);

// do your main work ...

for(i=0;i<(1<<26);i++) ;

// your main work complete, end the thread
ok_to_exit=1;
pthread_join(ptid, (void**)&ret_buf);
fprintf(stdout,"thread returned: %s\n",ret_buf);

return 0;
}
binb 2000-06-11
  • 打赏
  • 举报
回复
请问新进程能执行主进程的子程序吗?
最好举个例子!
hu_zy 2000-06-11
  • 打赏
  • 举报
回复
用fork建一个新进程!
kxy 2000-06-11
  • 打赏
  • 举报
回复
哥们儿,你是不是不看书的:)
binb 2000-06-11
  • 打赏
  • 举报
回复
to kxy
虽然也编了几十万行程序,确实很少看书
请推荐几本好书

19,612

社区成员

发帖
与我相关
我的任务
社区描述
系统使用、管理、维护问题。可以是Ubuntu, Fedora, Unix等等
社区管理员
  • 系统维护与使用区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧