当前位置: 技术问答>linux和unix
如何判断一个文件被其它进程占用
来源: 互联网 发布时间:2016-09-18
本文导语: 我有两个进程, A用来写文件, B用来读取A写的文件. 要求是, B不能读取这个文件, 直到A写全文件为止. 但现在的问题是, A进程是我不能控制的, 用exec打开的, 我没法在A进程里对文件上锁什么的. 那请问, 是否有...
我有两个进程, A用来写文件, B用来读取A写的文件.
要求是, B不能读取这个文件, 直到A写全文件为止.
但现在的问题是, A进程是我不能控制的, 用exec打开的, 我没法在A进程里对文件上锁什么的.
那请问, 是否有办法在B进程中, 来判断这个文件是否被其它进程占用, 如果被占用着, 那就暂时不打开.
谢谢!
要求是, B不能读取这个文件, 直到A写全文件为止.
但现在的问题是, A进程是我不能控制的, 用exec打开的, 我没法在A进程里对文件上锁什么的.
那请问, 是否有办法在B进程中, 来判断这个文件是否被其它进程占用, 如果被占用着, 那就暂时不打开.
谢谢!
|
#include
FILE *
popen(const char *command, const char *mode);
int
pclose(FILE *stream);
DESCRIPTION
The popen() function ``opens'' a process by creating a bidirectional
pipe, forking, and invoking the shell. Any streams opened by previous
popen() calls in the parent process are closed in the new child process.
Historically, popen() was implemented with a unidirectional pipe; hence,
many implementations of popen() only allow the mode argument to specify
reading or writing, not both. Because popen() is now implemented using a
bidirectional pipe, the mode argument may request a bidirectional data
flow. The mode argument is a pointer to a null-terminated string which
must be `r' for reading, `w' for writing, or `r+' for reading and writ-
ing.
The command argument is a pointer to a null-terminated string containing
a shell command line. This command is passed to /bin/sh, using the -c
flag; interpretation, if any, is performed by the shell.
The return value from popen() is a normal standard I/O stream in all
respects, save that it must be closed with pclose() rather than fclose().
Writing to such a stream writes to the standard input of the command; the
command's standard output is the same as that of the process that called
popen(), unless this is altered by the command itself. Conversely, read-
ing from a ``popened'' stream reads the command's standard output, and
the command's standard input is the same as that of the process that
called popen().
Note that output popen() streams are fully buffered, by default.
The pclose() function waits for the associated process to terminate; it
returns the exit status of the command, as returned by wait4(2).
RETURN VALUES
The popen() function returns NULL if the fork(2) or pipe(2) calls fail,
or if it cannot allocate memory.
The pclose() function returns -1 if stream is not associated with a
``popened'' command, if stream already ``pclosed'', or if wait4(2)
returns an error.
|
lsof | grep filename
如果有输出(或者退出状态$?=0) 表示filename正在被操作
如果没输出(或者退出状态非0) 表示filename没在被操作
如果有输出(或者退出状态$?=0) 表示filename正在被操作
如果没输出(或者退出状态非0) 表示filename没在被操作