導航:首頁 > 編程語言 > pythonosread

pythonosread

發布時間:2023-02-07 00:39:32

python os.system、os.popen、subprocess.Popen的區別

1、使用os.system("cmd")

這是最簡單的一種方法,其執行過程中會輸出顯示cmd命令執行的信息。

例如:print os.system("mkdir test") >>>輸出:0

可以看到結果列印出0,表示命令執行成功;否則表示失敗(再次執行該命令,輸出:子目錄或文件 test 已經存在。1)。

2、使用os.popen("cmd")

通過os.popen()返回的是 file read 的對象,對其進行讀取read()操作可以看到執行的輸出

例如:print os.popen("adb shell ls /sdcard/ | findstr aa.png").read() >>> 輸出:aa.png(若aa.png存在,否則輸出為空)

3、subprocess.Popen("cmd")

subprocess模塊被推薦用來替換一些老的模塊和函數,如:os.system、os.spawn*、os.popen*等

subprocess模塊目的是 啟動一個新的進程並與之通信 ,最常用是定義類Popen,使用Popen可以創建進程,並與進程進行復雜的交互。其函數原型為:

classsubprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)

Popen非常強大,支持多種參數和模式,通過其構造函數可以看到支持很多參數。但Popen函數存在缺陷在於, 它是一個阻塞的方法 ,如果運行cmd命令時產生內容非常多,函數就容易阻塞。另一點, Popen方法也不會列印出cmd的執行信息 。

以下羅列常用到的參數:

args :這個參數必須是 字元串 或者是一個由 字元串成員的列表 。其中如果是一個字元串列表的話,那第一個成員為要運行的程序的路徑以及程序名稱;從第二個成員開始到最後一個成員為運行這個程序需要輸入的參數。這與popen中是一樣的。

bufsize: 一般使用比較少,略過。

executable: 指定要運行的程序,這個一般很少用到,因為要指定運行的程序在args中已經指定了。 stdin,stdout ,stderr: 分別代表程序的標准輸入、標准輸出、標准錯誤處理。可以選擇的值有 PIPE , 已經存在的打開的文件對象 和 NONE 。若stdout是文件對象的話,要確保文件對象是處於打開狀態。

shell:shell參數根據要執行的命令情況來定,如果將參數shell設為True,executable將指定程序使用的shell。在windows平台下,默認的shell由COMSPEC環境變數來指定。

② python os.rename 報錯OSError: [Errno 2] No such file or directory

for APK in apklist:
portion = os.path.splitext(APK)

if portion[1] == ".apk":
newname = portion[0] + ".zip"
os.rename(os.path.join(path,APK),newname) #os.rename是在當前目錄下操作,是不是得加上path這個路徑

③ python 基礎教程

運算

a = 21
b = 10
c = 0

c = a + b
print "1 - c 的值為:", c

c = a - b
print "2 - c 的值為:", c

c = a * b
print "3 - c 的值為:", c

c = a / b
print "4 - c 的值為:", c

c = a % b
print "5 - c 的值為:", c

a = 2
b = 3
c = a**b
print "6 - c 的值為:", c

a = 10
b = 5
c = a//b
print "7 - c 的值為:", c

python比較

a = 21
b = 10
c = 0

if ( a == b ):
print "1 - a 等於 b"
else:
print "1 - a 不等於 b"

if ( a != b ):
print "2 - a 不等於 b"
else:
print "2 - a 等於 b"

if ( a <> b ):
print "3 - a 不等於 b"
else:
print "3 - a 等於 b"

if ( a < b ):
print "4 - a 小於 b"
else:
print "4 - a 大於等於 b"

if ( a > b ):
print "5 - a 大於 b"
else:
print "5 - a 小於等於 b"

a = 5
b = 20
if ( a <= b ):
print "6 - a 小於等於 b"
else:
print "6 - a 大於 b"

if ( b >= a ):
print "7 - b 大於等於 a"
else:
print "7 - b 小於 a"

賦值

a = 21
b = 10
c = 0

c = a + b
print "1 - c 的值為:", c

c += a
print "2 - c 的值為:", c

c *= a
print "3 - c 的值為:", c

c /= a
print "4 - c 的值為:", c

c = 2
c %= a
print "5 - c 的值為:", c

c **= a
print "6 - c 的值為:", c

c //= a
print "7 - c 的值為:", c

邏輯運算符:

a = 10
b = 20

if ( a and b ):
print "1 - 變數 a 和 b 都為 true"
else:
print "1 - 變數 a 和 b 有一個不為 true"

if ( a or b ):
print "2 - 變數 a 和 b 都為 true,或其中一個變數為 true"
else:
print "2 - 變數 a 和 b 都不為 true"

a = 0
if ( a and b ):
print "3 - 變數 a 和 b 都為 true"
else:
print "3 - 變數 a 和 b 有一個不為 true"

if ( a or b ):
print "4 - 變數 a 和 b 都為 true,或其中一個變數為 true"
else:
print "4 - 變數 a 和 b 都不為 true"

if not( a and b ):
print "5 - 變數 a 和 b 都為 false,或其中一個變數為 false"
else:
print "5 - 變數 a 和 b 都為 true"

in,not in

a = 10
b = 20
list = [1, 2, 3, 4, 5 ];

if ( a in list ):
print "1 - 變數 a 在給定的列表中 list 中"
else:
print "1 - 變數 a 不在給定的列表中 list 中"

if ( b not in list ):
print "2 - 變數 b 不在給定的列表中 list 中"
else:
print "2 - 變數 b 在給定的列表中 list 中"

a = 2
if ( a in list ):
print "3 - 變數 a 在給定的列表中 list 中"
else:
print "3 - 變數 a 不在給定的列表中 list 中"

條件

flag = False
name = 'luren'
if name == 'python': # 判斷變數否為'python'
flag = True # 條件成立時設置標志為真
print 'welcome boss' # 並輸出歡迎信息
else:
print name

num = 5
if num == 3: # 判斷num的值
print 'boss'
elif num == 2:
print 'user'
elif num == 1:
print 'worker'
elif num < 0: # 值小於零時輸出
print 'error'
else:
print 'roadman' # 條件均不成立時輸出

循環語句:

count = 0
while (count < 9):
print 'The count is:', count
count = count + 1

print "Good bye!"

i = 1
while i < 10:
i += 1
if i%2 > 0: # 非雙數時跳過輸出
continue
print i # 輸出雙數2、4、6、8、10

i = 1
while 1: # 循環條件為1必定成立
print i # 輸出1~10
i += 1
if i > 10: # 當i大於10時跳出循環
break

for letter in 'Python': # 第一個實例
print '當前字母 :', letter

fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # 第二個實例
print '當前水果 :', fruit

print "Good bye!"

獲取用戶輸入:raw_input

var = 1
while var == 1 : # 該條件永遠為true,循環將無限執行下去
num = raw_input("Enter a number :")
print "You entered: ", num

print "Good bye!"

range,len

fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print '當前水果 :', fruits[index]

print "Good bye!"

python數學函數:
abs,cell,cmp,exp,fabs,floor,log,log10,max,min,mod,pow,round,sqrt

randrange

訪問字元串的值

var1 = 'Hello World!'
var2 = "Python Runoob"

print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]

轉義字元

格式化輸出
print "My name is %s and weight is %d kg!" % ('Zara', 21)

字元串函數:

添加元素

list = [] ## 空列表
list.append('Google') ## 使用 append() 添加元素
list.append('Runoob')
print list

刪除元素

list1 = ['physics', 'chemistry', 1997, 2000]

print list1
del list1[2]
print "After deleting value at index 2 : "
print list1

列表操作

列表方法

刪除字典

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

del dict['Name']; # 刪除鍵是'Name'的條目
dict.clear(); # 清空詞典所有條目
del dict ; # 刪除詞典

print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];

字典的函數:

當前時間戳:
import time
time.time()

格式化日期輸出

import time

print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

print time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())

a = "Sat Mar 28 22:24:24 2016"
print time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y"))

獲取某個月日歷:calendar

import calendar

cal = calendar.month(2016, 1)
print "以下輸出2016年1月份的日歷:"
print cal

當前日期和時間

import datetime
i = datetime.datetime.now()
print ("當前的日期和時間是 %s" % i)
print ("ISO格式的日期和時間是 %s" % i.isoformat() )
print ("當前的年份是 %s" %i.year)
print ("當前的月份是 %s" %i.month)
print ("當前的日期是 %s" %i.day)
print ("dd/mm/yyyy 格式是 %s/%s/%s" % (i.day, i.month, i.year) )
print ("當前小時是 %s" %i.hour)
print ("當前分鍾是 %s" %i.minute)
print ("當前秒是 %s" %i.second)

不定長參數:*

lambda:匿名函數

def....

python模塊搜索路徑

獲取用戶輸入

str = raw_input("請輸入:")
print "你輸入的內容是: ", str

input可以接收表達式

open參數

write要自己添加換行符

讀取10個字元

重命名:os.rename
os.remove
os.mkdir os.chdir
os.getcwd
os.rmdir

open參數

file的方法

異常:

try:
fh = open("testfile", "w")
fh.write("這是一個測試文件,用於測試異常!!")
except IOError:
print "Error: 沒有找到文件或讀取文件失敗"
else:
print "內容寫入文件成功"
fh.close()

try:
fh = open("testfile", "w")
fh.write("這是一個測試文件,用於測試異常!!")
finally:
print "Error: 沒有找到文件或讀取文件失敗"

用戶自定義異常:

os 模塊提供了非常豐富的方法用來處理文件和目錄。常用的方法如下表所示:

| 序號 | 方法及描述 |
| 1 |

os.access(path, mode)

檢驗許可權模式 |
| 2 |

os.chdir(path)

改變當前工作目錄 |
| 3 |

os.chflags(path, flags)

設置路徑的標記為數字標記。 |
| 4 |

os.chmod(path, mode)

更改許可權 |
| 5 |

os.chown(path, uid, gid)

更改文件所有者 |
| 6 |

os.chroot(path)

改變當前進程的根目錄 |
| 7 |

os.close(fd)

關閉文件描述符 fd |
| 8 |

os.closerange(fd_low, fd_high)

關閉所有文件描述符,從 fd_low (包含) 到 fd_high (不包含), 錯誤會忽略 |
| 9 |

os.p(fd)

復制文件描述符 fd |
| 10 |

os.p2(fd, fd2)

將一個文件描述符 fd 復制到另一個 fd2 |
| 11 |

os.fchdir(fd)

通過文件描述符改變當前工作目錄 |
| 12 |

os.fchmod(fd, mode)

改變一個文件的訪問許可權,該文件由參數fd指定,參數mode是Unix下的文件訪問許可權。 |
| 13 |

os.fchown(fd, uid, gid)

修改一個文件的所有權,這個函數修改一個文件的用戶ID和用戶組ID,該文件由文件描述符fd指定。 |
| 14 |

os.fdatasync(fd)

強制將文件寫入磁碟,該文件由文件描述符fd指定,但是不強制更新文件的狀態信息。 |
| 15 |

os.fdopen(fd[, mode[, bufsize]])

通過文件描述符 fd 創建一個文件對象,並返回這個文件對象 |
| 16 |

os.fpathconf(fd, name)

返回一個打開的文件的系統配置信息。name為檢索的系統配置的值,它也許是一個定義系統值的字元串,這些名字在很多標准中指定(POSIX.1, Unix 95, Unix 98, 和其它)。 |
| 17 |

os.fstat(fd)

返迴文件描述符fd的狀態,像stat()。 |
| 18 |

os.fstatvfs(fd)

返回包含文件描述符fd的文件的文件系統的信息,像 statvfs() |
| 19 |

os.fsync(fd)

強制將文件描述符為fd的文件寫入硬碟。 |
| 20 |

os.ftruncate(fd, length)

裁剪文件描述符fd對應的文件, 所以它最大不能超過文件大小。 |
| 21 |

os.getcwd()

返回當前工作目錄 |
| 22 |

os.getcw()

返回一個當前工作目錄的Unicode對象 |
| 23 |

os.isatty(fd)

如果文件描述符fd是打開的,同時與tty(-like)設備相連,則返回true, 否則False。 |
| 24 |

os.lchflags(path, flags)

設置路徑的標記為數字標記,類似 chflags(),但是沒有軟鏈接 |
| 25 |

os.lchmod(path, mode)

修改連接文件許可權 |
| 26 |

os.lchown(path, uid, gid)

更改文件所有者,類似 chown,但是不追蹤鏈接。 |
| 27 |

os.link(src, dst)

創建硬鏈接,名為參數 dst,指向參數 src |
| 28 |

os.listdir(path)

返回path指定的文件夾包含的文件或文件夾的名字的列表。 |
| 29 |

os.lseek(fd, pos, how)

設置文件描述符 fd當前位置為pos, how方式修改: SEEK_SET 或者 0 設置從文件開始的計算的pos; SEEK_CUR或者 1 則從當前位置計算; os.SEEK_END或者2則從文件尾部開始. 在unix,Windows中有效 |
| 30 |

os.lstat(path)

像stat(),但是沒有軟鏈接 |
| 31 |

os.major(device)

從原始的設備號中提取設備major號碼 (使用stat中的st_dev或者st_rdev field)。 |
| 32 |

os.makedev(major, minor)

以major和minor設備號組成一個原始設備號 |
| 33 |

os.makedirs(path[, mode])

遞歸文件夾創建函數。像mkdir(), 但創建的所有intermediate-level文件夾需要包含子文件夾。 |
| 34 |

os.minor(device)

從原始的設備號中提取設備minor號碼 (使用stat中的st_dev或者st_rdev field )。 |
| 35 |

os.mkdir(path[, mode])

以數字mode的mode創建一個名為path的文件夾.默認的 mode 是 0777 (八進制)。 |
| 36 |

os.mkfifo(path[, mode])

創建命名管道,mode 為數字,默認為 0666 (八進制) |
| 37 |

os.mknod(filename[, mode=0600, device])
創建一個名為filename文件系統節點(文件,設備特別文件或者命名pipe)。

|
| 38 |

os.open(file, flags[, mode])

打開一個文件,並且設置需要的打開選項,mode參數是可選的 |
| 39 |

os.openpty()

打開一個新的偽終端對。返回 pty 和 tty的文件描述符。 |
| 40 |

os.pathconf(path, name)

返回相關文件的系統配置信息。 |
| 41 |

os.pipe()

創建一個管道. 返回一對文件描述符(r, w) 分別為讀和寫 |
| 42 |

os.popen(command[, mode[, bufsize]])

從一個 command 打開一個管道 |
| 43 |

os.read(fd, n)

從文件描述符 fd 中讀取最多 n 個位元組,返回包含讀取位元組的字元串,文件描述符 fd對應文件已達到結尾, 返回一個空字元串。 |
| 44 |

os.readlink(path)

返回軟鏈接所指向的文件 |
| 45 |

os.remove(path)

刪除路徑為path的文件。如果path 是一個文件夾,將拋出OSError; 查看下面的rmdir()刪除一個 directory。 |
| 46 |

os.removedirs(path)

遞歸刪除目錄。 |
| 47 |

os.rename(src, dst)

重命名文件或目錄,從 src 到 dst |
| 48 |

os.renames(old, new)

遞歸地對目錄進行更名,也可以對文件進行更名。 |
| 49 |

os.rmdir(path)

刪除path指定的空目錄,如果目錄非空,則拋出一個OSError異常。 |
| 50 |

os.stat(path)

獲取path指定的路徑的信息,功能等同於C API中的stat()系統調用。 |
| 51 |

os.stat_float_times([newvalue])
決定stat_result是否以float對象顯示時間戳

|
| 52 |

os.statvfs(path)

獲取指定路徑的文件系統統計信息 |
| 53 |

os.symlink(src, dst)

創建一個軟鏈接 |
| 54 |

os.tcgetpgrp(fd)

返回與終端fd(一個由os.open()返回的打開的文件描述符)關聯的進程組 |
| 55 |

os.tcsetpgrp(fd, pg)

設置與終端fd(一個由os.open()返回的打開的文件描述符)關聯的進程組為pg。 |
| 56 |

os.tempnam([dir[, prefix]])

返回唯一的路徑名用於創建臨時文件。 |
| 57 |

os.tmpfile()

返回一個打開的模式為(w+b)的文件對象 .這文件對象沒有文件夾入口,沒有文件描述符,將會自動刪除。 |
| 58 |

os.tmpnam()

為創建一個臨時文件返回一個唯一的路徑 |
| 59 |

os.ttyname(fd)

返回一個字元串,它表示與文件描述符fd 關聯的終端設備。如果fd 沒有與終端設備關聯,則引發一個異常。 |
| 60 |

os.unlink(path)

刪除文件路徑 |
| 61 |

os.utime(path, times)

返回指定的path文件的訪問和修改的時間。 |
| 62 |

os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])

輸出在文件夾中的文件名通過在樹中遊走,向上或者向下。 |
| 63 |

os.write(fd, str)

寫入字元串到文件描述符 fd中. 返回實際寫入的字元串長度 |

④ python語句 os.system os.popen什麼意思

os.system() 和os.popen()的區別
返回的數據不同

1 os.system(「ls") 返回0
但是這樣是無法獲得到輸出和返回值的
繼續 Google,之後學會了 os.popen()。 view sourceprint?
a... output = os.popen('cat /proc/cpuinfo')
b... print output.read()
os.system() returns the (encoded) process exit value. 0 means success:
輸出0為正確運行。1為出現異常。
如果你想得到標准輸出,可以使用 subprocess.check_output() 來代替這個方法
x = subprocess.check_output(['whoami'])

⑤ 如何學習python的os模塊

一、os模塊概述

Python os模塊包含普遍的操作系統功能。如果你希望你的程序能夠與平台無關的話,這個模塊是尤為重要的。(一語中的)

二、常用方法

1、os.name

輸出字元串指示正在使用的平台。如果是window 則用'nt'表示,對於linux/Unix用戶,它是'posix'。

2、os.getcwd()

函數得到當前工作目錄,即當前Python腳本工作的目錄路徑。

3、os.listdir()

返回指定目錄下的所有文件和目錄名。

>>> os.listdir(os.getcwd())
['Django', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'MySQL-python-wininst.log', 'NEWS.txt', 'PIL-wininst.log', 'python.exe', 'pythonw.exe', 'README.txt', 'RemoveMySQL-python.exe', 'RemovePIL.exe', 'Removesetuptools.exe', 'Scripts', 'setuptools-wininst.log', 'tcl', 'Tools', 'w9xpopen.exe']
>>>

4、os.remove()

刪除一個文件。

5、os.system()

運行shell命令。

>>> os.system('dir')
0
>>> os.system('cmd') #啟動dos

6、os.sep 可以取代操作系統特定的路徑分割符。

7、os.linesep字元串給出當前平台使用的行終止符

>>> os.linesep
'\r\n' #Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'。
>>> os.sep
'\\' #Windows
>>>

8、os.path.split()

函數返回一個路徑的目錄名和文件名

>>> os.path.split('C:\\Python25\\abc.txt')
('C:\\Python25', 'abc.txt')

9、os.path.isfile()和os.path.isdir()函數分別檢驗給出的路徑是一個文件還是目錄。

>>> os.path.isdir(os.getcwd())
True
>>> os.path.isfile('a.txt')
False

10、os.path.exists()函數用來檢驗給出的路徑是否真地存在

>>> os.path.exists('C:\\Python25\\abc.txt')
False
>>> os.path.exists('C:\\Python25')
True
>>>

11、os.path.abspath(name):獲得絕對路徑

12、os.path.normpath(path):規范path字元串形式

13、os.path.getsize(name):獲得文件大小,如果name是目錄返回0L

14、os.path.splitext():分離文件名與擴展名

>>> os.path.splitext('a.txt')
('a', '.txt')

15、os.path.join(path,name):連接目錄與文件名或目錄

>>> os.path.join('c:\\Python','a.txt')
'c:\\Python\\a.txt'
>>> os.path.join('c:\\Python','f1')
'c:\\Python\\f1'
>>>

16、os.path.basename(path):返迴文件名

>>> os.path.basename('a.txt')
'a.txt'
>>> os.path.basename('c:\\Python\\a.txt')
'a.txt'
>>>

17、os.path.dirname(path):返迴文件路徑

>>> os.path.dirname('c:\\Python\\a.txt')
'c:\\Python'

⑥ python,os.popen 打包後出現問題

你打包成exe後,命令行應該是pyinstller -Fw xxx.py
你加上了w參數也就是把console設置成了flase;那麼os.popen()或者subprocess.popen()執行的時候沒有載體,你只有把console設置成true,也就是命令改為pyinstaller -F xxx.py,這樣你的os.popen()可執行,也能獲得返回值。

⑦ 如何用python編程實現lspci的功能

lspci 是個linux 命令,可以用python 的os.popen/os.system/subprocess 等更使用系統shell

舉個栗子:

importos
#os.system
os.system("lspci")

#os.popen
os.popen("lspci").read()

Python 跟shell 溝通有很多種方式, 可以多查查pydoc。 希望有幫助

⑧ 如何用Python os.path.walk方法遍歷搜索文件內容的操作詳解

文中使用到了Python os模塊和Python sys模塊,這兩個模塊具體的使用方法請參考玩蛇網相關文章閱讀。
Python os.path.walk方法遍歷文件搜索內容方法代碼如下:
?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

import os, sys
#代碼中需要用到的方法模塊導入

listonly = False

skipexts = ['.gif', '.exe', '.pyc', '.o', '.a','.dll','.lib','.pdb','.mdb'] # ignore binary files

def visitfile(fname, searchKey):
global fcount, vcount
try:
if not listonly:
if os.path.splitext(fname)[1] in skipexts:
pass
elif open(fname).read().find(searchKey) != -1:
print'%s has %s' % (fname, searchKey)
fcount += 1
except: pass
vcount += 1

#www.iplaypy.com

def visitor(args, directoryName,filesInDirectory):
for fname in filesInDirectory:
fpath = os.path.join(directoryName, fname)
if not os.path.isdir(fpath):
visitfile(fpath,args)

def searcher(startdir, searchkey):
global fcount, vcount
fcount = vcount = 0
os.path.walk(startdir, visitor, searchkey)

if __name__ == '__main__':
root=raw_input("type root directory:")
key=raw_input("type key:")
searcher(root,key)
print 'Found in %d files, visited %d' % (fcount, vcount)

⑨ 如何操作 python os.popen的返回

ret = os.popen("ls").read()
但是,一些命令是不會輸出消息的,所以調用read的時候會阻塞,你需要注意一下

⑩ python編程中 os.mkfifo()和os.mknod()函數具體用法最好有例子,裡面參數具體怎麼配置就能創建管道或節

mkfifo函數使用
[code]mkfifo(建立實名管道)
相關函數
pipe,popen,open,umask
表頭文件
#include
#include
定義函數
int mkfifo(const char * pathname,mode_t mode);
函數說明
mkfifo() 會依參數pathname建立特殊的FIFO文件,該文件必須不存在,而參數mode為該文件的許可權(mode%~umask),因此 umask值也會影響到FIFO文件的許可權。Mkfifo()建立的FIFO文件其他進程都可以用讀寫一般文件的方式存取。當使用open()來打開 FIFO文件時,O_NONBLOCK旗標會有影響
1、當使用O_NONBLOCK 旗標時,打開FIFO 文件來讀取的操作會立刻返回,但是若還沒有其他進程打開FIFO 文件來讀取,則寫入的操作會返回ENXIO 錯誤代碼。
2、沒有使用O_NONBLOCK 旗標時,打開FIFO 來讀取的操作會等到其他進程打開FIFO文件來寫入才正常返回。同樣地,打開FIFO文件來寫入的操作會等到其他進程打開FIFO 文件來讀取後才正常返回。
返回值
若成功則返回0,否則返回-1,錯誤原因存於errno中。
錯誤代碼
EACCESS 參數pathname所指定的目錄路徑無可執行的許可權
EEXIST 參數pathname所指定的文件已存在。
ENAMETOOLONG 參數pathname的路徑名稱太長。
ENOENT 參數pathname包含的目錄不存在
ENOSPC 文件系統的剩餘空間不足
ENOTDIR 參數pathname路徑中的目錄存在但卻非真正的目錄。
EROFS 參數pathname指定的文件存在於只讀文件系統內。

示例1:
#include
#include
#include
#include

int main(void)
{
char buf[80];
int fd;
unlink( "zieckey_fifo" );
mkfifo( "zieckey_fifo", 0777 );

if ( fork() > 0 )
{
char s[] = "Hello!\n";
fd = open( "zieckey_fifo", O_WRONLY );
write( fd, s, sizeof(s) );
//close( fd );
}
else
{
fd = open( "zieckey_fifo", O_RDONLY );
read( fd, buf, sizeof(buf) );
printf("The message from the pipe is:%s\n", buf );
//close( fd );
}

return 0;
}
執行
hello!

示例2:
#include
#include
#include
#include
#include

int main( int argc, char **argv )
{
mode_t mode = 0666;
if ( argc !=2 )
{
printf( "Usage:[%s] fifo_filename\n", argv[0] );
return -1;
}

if (mkfifo( argv[1], mode)<0 )
{
perror( "mkfifo");
return -1;
}

return 0;
} [/code]

閱讀全文

與pythonosread相關的資料

熱點內容
身體不好當程序員 瀏覽:274
mount命令作用 瀏覽:220
畫江湖之不良人黑白無常雙修刪減 瀏覽:754
朵唯手機如何加密 瀏覽:504
安卓雙清指的什麼 瀏覽:177
phpredis所有keys 瀏覽:988
朋友賣房要解壓嗎 瀏覽:108
sar命令安裝 瀏覽:169
安卓怎麼看我自己去過哪裡 瀏覽:283
演算法分析里log沒有底數嗎 瀏覽:222
伺服器卡頓怎麼連接 瀏覽:957
手機拍照文件夾自動生成 瀏覽:788
瀏覽器如何運行在伺服器端 瀏覽:790
collinux 瀏覽:449
日本歐美韓國推理片電影大分享 瀏覽:615
怎麼下載香港app游戲 瀏覽:217
加密貨幣或迎來新的上漲趨勢 瀏覽:827
電腦桌面的文件夾怎麼發的 瀏覽:194
linuxkangle 瀏覽:150
程序員負債 瀏覽:154