怎么判断我的程序已经运行了?

zly1980 2004-12-10 07:35:27
怎么判断我的程序已经运行了?
int main(int argc,char **argv)
{
if (fork()) exit(0);
if (fork()) exit(0);
setsid();
close(0);
close(1);
close(2);
for(;;)
{;//my code here}
return 0;
}
一个这样的程序,可以后台运行的,就是在终端运行的时候运行了就返回控制给终端的,但是我要程序只运行一次,如果运行了就不再运行了.
...全文
195 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
wangjinhu 2004-12-22
  • 打赏
  • 举报
回复
ps -ef|grep your.out
tengulre 2004-12-16
  • 打赏
  • 举报
回复
UP
yunheehust 2004-12-16
  • 打赏
  • 举报
回复
ps -A|grep yourapp
litw 2004-12-16
  • 打赏
  • 举报
回复
最方便的方法,对ps结果作判断
lifeixiao 2004-12-15
  • 打赏
  • 举报
回复
用一个文件来记录启动信息,每次启动去查询这个文件。
pubol 2004-12-15
  • 打赏
  • 举报
回复
转载:
在程序运行的时候,创建一个.pid的文件,然后以非阻塞的方式
对文件上独占锁,只要返回OK,就可以认为OK.

#if 1
FILE * pidfp;
int8 pidstr[80];

pidfp = fopen(".pid","r+");
if( pidfp == NULL )
{
pidfp = fopen(".pid","w");
if( NULL == pidfp )
{
printf("打开文件.pid失败:%s\n",strerror(errno));
return 0;
}
}
if( NULL != pidfp )
{
int retcode;
int fd;
int type;

memset(pidstr,'\0',sizeof(pidstr));
fgets(pidstr,80,pidfp);
pidstr[80-1] = '\0';
rewind(pidfp);

fd = fileno(pidfp);
type = AFC_LOCK_EX | AFC_LOCK_NB;
{
struct flock sLock;
struct stat sStat;
int cmd = 0;
int retcode;

retcode = fstat(fd,&sStat);
...
memset(&sLock,'\0',sizeof(sLock));
sLock.l_type = F_RDLCK;
sLock.l_whence = SEEK_SET;
sLock.l_start = 0;
sLock.l_len = 0;
retcode = fcntl(fd,F_GETLK,&sLock);
if( 0 != retcode )
....
if( (AFC_LOCK_NB & type) == 0 )
cmd = F_SETLKW;
else
cmd = F_SETLK;
while(1)
{
if( (AFC_LOCK_EX & type) != 0 )
{
sLock.l_type = F_WRLCK;
retcode = fcntl(fd,cmd,&sLock);
}
else if( (AFC_LOCK_SH & type) != 0 )
{
sLock.l_type = F_RDLCK ;
retcode = fcntl(fd,cmd,&sLock);
}
if( -1 == retcode )
{
if ( EINTR == errno )
{
errno = 0;
continue;
}
else if( cmd != F_SETLK )
{
WriteLog("fcntl:F_SETLKW失败:%s",strerror(errno) );
break;
}
}
break;
}
}
if( retcode == -1 )
{
printf("进程已经启动了\n");
fprintf(pidfp,"%s",pidstr);
fclose(pidfp);
return 0;
}

fprintf(pidfp,"%d",getpid());
fflush(pidfp);
}
#endif

另外共享内存、判断ps、使用信号量的方法也可以使用试下
linaxing 2004-12-11
  • 打赏
  • 举报
回复
用锁来实现吧,启动的时候查询一下,如果所已经加了就说明程序以及运行了。

23,121

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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