2 /* POSIX module implementation */
4 /* This file is also used for Windows NT/MS-Win and OS/2. In that case the
5 module actually calls itself 'nt' or 'os2', not 'posix', and a few
6 functions are either unimplemented or implemented differently. The source
7 assumes that for Windows NT, the macro 'MS_WINDOWS' is defined independent
8 of the compiler used. Different compilers define their own feature
9 test macro, e.g. '__BORLANDC__' or '_MSC_VER'. For OS/2, the compiler
10 independent macro PYOS_OS2 should be defined. On OS/2 the default
11 compiler is assumed to be IBM's VisualAge C++ (VACPP). PYCC_GCC is used
12 as the compiler specific macro for the EMX port of gcc to OS/2. */
14 /* See also ../Dos/dosmodule.c */
18 * Step 1 of support for weak-linking a number of symbols existing on
19 * OSX 10.4 and later, see the comment in the #ifdef __APPLE__ block
20 * at the end of this file for more information.
24 # pragma weak fstatvfs
26 #endif /* __APPLE__ */
28 #define PY_SSIZE_T_CLEAN
31 #include "structseq.h"
35 #endif /* defined(__VMS) */
41 PyDoc_STRVAR(posix__doc__
,
42 "This module provides access to operating system functionality that is\n\
43 standardized by the C Standard and the POSIX standard (a thinly\n\
44 disguised Unix interface). Refer to the library manual and\n\
45 corresponding Unix manual entries for more information on calls.");
47 #ifndef Py_USING_UNICODE
48 /* This is used in signatures of functions. */
49 #define Py_UNICODE void
54 #define INCL_DOSERRORS
55 #define INCL_DOSPROCESS
67 #ifdef HAVE_SYS_TYPES_H
68 #include <sys/types.h>
69 #endif /* HAVE_SYS_TYPES_H */
71 #ifdef HAVE_SYS_STAT_H
73 #endif /* HAVE_SYS_STAT_H */
75 #ifdef HAVE_SYS_WAIT_H
76 #include <sys/wait.h> /* For WNOHANG */
85 #endif /* HAVE_FCNTL_H */
91 #ifdef HAVE_SYSEXITS_H
93 #endif /* HAVE_SYSEXITS_H */
95 #ifdef HAVE_SYS_LOADAVG_H
96 #include <sys/loadavg.h>
99 /* Various compilers have only certain posix functions */
100 /* XXX Gosh I wish these were all moved into pyconfig.h */
101 #if defined(PYCC_VACPP) && defined(PYOS_OS2)
104 #if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */
105 #define HAVE_GETCWD 1
106 #define HAVE_OPENDIR 1
107 #define HAVE_SYSTEM 1
114 #ifdef __BORLANDC__ /* Borland compiler */
116 #define HAVE_GETCWD 1
117 #define HAVE_OPENDIR 1
120 #define HAVE_SYSTEM 1
123 #ifdef _MSC_VER /* Microsoft compiler */
124 #define HAVE_GETCWD 1
125 #define HAVE_SPAWNV 1
129 #define HAVE_SYSTEM 1
132 #define fsync _commit
134 #if defined(PYOS_OS2) && defined(PYCC_GCC) || defined(__VMS)
135 /* Everything needed is defined in PC/os2emx/pyconfig.h or vms/pyconfig.h */
136 #else /* all other compilers */
137 /* Unix functions that the configure script doesn't check for */
140 #if defined(__USLC__) && defined(__SCO_VERSION__) /* SCO UDK Compiler */
143 #define HAVE_GETCWD 1
144 #define HAVE_GETEGID 1
145 #define HAVE_GETEUID 1
146 #define HAVE_GETGID 1
147 #define HAVE_GETPPID 1
148 #define HAVE_GETUID 1
150 #define HAVE_OPENDIR 1
155 #define HAVE_SYSTEM 1
157 #define HAVE_TTYNAME 1
158 #endif /* PYOS_OS2 && PYCC_GCC && __VMS */
159 #endif /* _MSC_VER */
160 #endif /* __BORLANDC__ */
161 #endif /* ! __WATCOMC__ || __QNX__ */
162 #endif /* ! __IBMC__ */
166 #if defined(__sgi)&&_COMPILER_VERSION>=700
167 /* declare ctermid_r if compiling with MIPSPro 7.x in ANSI C mode
169 extern char *ctermid_r(char *);
172 #ifndef HAVE_UNISTD_H
173 #if defined(PYCC_VACPP)
174 extern int mkdir(char *);
176 #if ( defined(__WATCOMC__) || defined(_MSC_VER) ) && !defined(__QNX__)
177 extern int mkdir(const char *);
179 extern int mkdir(const char *, mode_t
);
182 #if defined(__IBMC__) || defined(__IBMCPP__)
183 extern int chdir(char *);
184 extern int rmdir(char *);
186 extern int chdir(const char *);
187 extern int rmdir(const char *);
190 extern int chmod(const char *, int);
192 extern int chmod(const char *, mode_t
);
194 extern int chown(const char *, uid_t
, gid_t
);
195 extern char *getcwd(char *, int);
196 extern char *strerror(int);
197 extern int link(const char *, const char *);
198 extern int rename(const char *, const char *);
199 extern int stat(const char *, struct stat
*);
200 extern int unlink(const char *);
201 extern int pclose(FILE *);
203 extern int symlink(const char *, const char *);
204 #endif /* HAVE_SYMLINK */
206 extern int lstat(const char *, struct stat
*);
207 #endif /* HAVE_LSTAT */
208 #endif /* !HAVE_UNISTD_H */
210 #endif /* !_MSC_VER */
214 #endif /* HAVE_UTIME_H */
216 #ifdef HAVE_SYS_UTIME_H
217 #include <sys/utime.h>
218 #define HAVE_UTIME_H /* pretend we do for the rest of this file */
219 #endif /* HAVE_SYS_UTIME_H */
221 #ifdef HAVE_SYS_TIMES_H
222 #include <sys/times.h>
223 #endif /* HAVE_SYS_TIMES_H */
225 #ifdef HAVE_SYS_PARAM_H
226 #include <sys/param.h>
227 #endif /* HAVE_SYS_PARAM_H */
229 #ifdef HAVE_SYS_UTSNAME_H
230 #include <sys/utsname.h>
231 #endif /* HAVE_SYS_UTSNAME_H */
235 #define NAMLEN(dirent) strlen((dirent)->d_name)
237 #if defined(__WATCOMC__) && !defined(__QNX__)
239 #define NAMLEN(dirent) strlen((dirent)->d_name)
241 #define dirent direct
242 #define NAMLEN(dirent) (dirent)->d_namlen
244 #ifdef HAVE_SYS_NDIR_H
245 #include <sys/ndir.h>
247 #ifdef HAVE_SYS_DIR_H
262 #ifdef HAVE_PROCESS_H
267 #include <shellapi.h> /* for ShellExecute() */
269 #define pclose _pclose
270 #endif /* _MSC_VER */
272 #if defined(PYCC_VACPP) && defined(PYOS_OS2)
277 #if defined(PATH_MAX) && PATH_MAX > 1024
278 #define MAXPATHLEN PATH_MAX
280 #define MAXPATHLEN 1024
282 #endif /* MAXPATHLEN */
285 /* Emulate some macros on systems that have a union instead of macros */
288 #define WIFEXITED(u_wait) (!(u_wait).w_termsig && !(u_wait).w_coredump)
292 #define WEXITSTATUS(u_wait) (WIFEXITED(u_wait)?((u_wait).w_retcode):-1)
296 #define WTERMSIG(u_wait) ((u_wait).w_termsig)
299 #define WAIT_TYPE union wait
300 #define WAIT_STATUS_INT(s) (s.w_status)
302 #else /* !UNION_WAIT */
303 #define WAIT_TYPE int
304 #define WAIT_STATUS_INT(s) (s)
305 #endif /* UNION_WAIT */
307 /* Don't use the "_r" form if we don't need it (also, won't have a
308 prototype for it, at least on Solaris -- maybe others as well?). */
309 #if defined(HAVE_CTERMID_R) && defined(WITH_THREAD)
310 #define USE_CTERMID_R
313 #if defined(HAVE_TMPNAM_R) && defined(WITH_THREAD)
317 /* choose the appropriate stat and fstat functions and return structs */
319 #if defined(MS_WIN64) || defined(MS_WINDOWS)
320 # define STAT win32_stat
321 # define FSTAT win32_fstat
322 # define STRUCT_STAT struct win32_stat
326 # define STRUCT_STAT struct stat
329 #if defined(MAJOR_IN_MKDEV)
330 #include <sys/mkdev.h>
332 #if defined(MAJOR_IN_SYSMACROS)
333 #include <sys/sysmacros.h>
335 #if defined(HAVE_MKNOD) && defined(HAVE_SYS_MKDEV_H)
336 #include <sys/mkdev.h>
340 /* Return a dictionary corresponding to the POSIX environment table */
341 #ifdef WITH_NEXT_FRAMEWORK
342 /* On Darwin/MacOSX a shared library or framework has no access to
343 ** environ directly, we must obtain it with _NSGetEnviron().
345 #include <crt_externs.h>
346 static char **environ
;
347 #elif !defined(_MSC_VER) && ( !defined(__WATCOMC__) || defined(__QNX__) )
348 extern char **environ
;
349 #endif /* !_MSC_VER */
359 #ifdef WITH_NEXT_FRAMEWORK
361 environ
= *_NSGetEnviron();
365 /* This part ignores errors */
366 for (e
= environ
; *e
!= NULL
; e
++) {
369 char *p
= strchr(*e
, '=');
372 k
= PyString_FromStringAndSize(*e
, (int)(p
-*e
));
377 v
= PyString_FromString(p
+1);
383 if (PyDict_GetItem(d
, k
) == NULL
) {
384 if (PyDict_SetItem(d
, k
, v
) != 0)
390 #if defined(PYOS_OS2)
393 char buffer
[1024]; /* OS/2 Provides a Documented Max of 1024 Chars */
395 rc
= DosQueryExtLIBPATH(buffer
, BEGIN_LIBPATH
);
396 if (rc
== NO_ERROR
) { /* (not a type, envname is NOT 'BEGIN_LIBPATH') */
397 PyObject
*v
= PyString_FromString(buffer
);
398 PyDict_SetItemString(d
, "BEGINLIBPATH", v
);
401 rc
= DosQueryExtLIBPATH(buffer
, END_LIBPATH
);
402 if (rc
== NO_ERROR
) { /* (not a typo, envname is NOT 'END_LIBPATH') */
403 PyObject
*v
= PyString_FromString(buffer
);
404 PyDict_SetItemString(d
, "ENDLIBPATH", v
);
413 /* Set a POSIX-specific error from errno, and return NULL */
418 return PyErr_SetFromErrno(PyExc_OSError
);
421 posix_error_with_filename(char* name
)
423 return PyErr_SetFromErrnoWithFilename(PyExc_OSError
, name
);
426 #ifdef Py_WIN_WIDE_FILENAMES
428 posix_error_with_unicode_filename(Py_UNICODE
* name
)
430 return PyErr_SetFromErrnoWithUnicodeFilename(PyExc_OSError
, name
);
432 #endif /* Py_WIN_WIDE_FILENAMES */
436 posix_error_with_allocated_filename(char* name
)
438 PyObject
*rc
= PyErr_SetFromErrnoWithFilename(PyExc_OSError
, name
);
445 win32_error(char* function
, char* filename
)
447 /* XXX We should pass the function name along in the future.
448 (_winreg.c also wants to pass the function name.)
449 This would however require an additional param to the
450 Windows error object, which is non-trivial.
452 errno
= GetLastError();
454 return PyErr_SetFromWindowsErrWithFilename(errno
, filename
);
456 return PyErr_SetFromWindowsErr(errno
);
459 #ifdef Py_WIN_WIDE_FILENAMES
461 win32_error_unicode(char* function
, Py_UNICODE
* filename
)
463 /* XXX - see win32_error for comments on 'function' */
464 errno
= GetLastError();
466 return PyErr_SetFromWindowsErrWithUnicodeFilename(errno
, filename
);
468 return PyErr_SetFromWindowsErr(errno
);
471 static PyObject
*_PyUnicode_FromFileSystemEncodedObject(register PyObject
*obj
)
475 /* Function suitable for O& conversion */
477 convert_to_unicode(PyObject
*arg
, void* _param
)
479 PyObject
**param
= (PyObject
**)_param
;
480 if (PyUnicode_CheckExact(arg
)) {
484 else if (PyUnicode_Check(arg
)) {
485 /* For a Unicode subtype that's not a Unicode object,
486 return a true Unicode object with the same data. */
487 *param
= PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(arg
),
488 PyUnicode_GET_SIZE(arg
));
489 return *param
!= NULL
;
492 *param
= PyUnicode_FromEncodedObject(arg
,
493 Py_FileSystemDefaultEncoding
,
495 return (*param
) != NULL
;
498 #endif /* Py_WIN_WIDE_FILENAMES */
502 #if defined(PYOS_OS2)
503 /**********************************************************************
504 * Helper Function to Trim and Format OS/2 Messages
505 **********************************************************************/
507 os2_formatmsg(char *msgbuf
, int msglen
, char *reason
)
509 msgbuf
[msglen
] = '\0'; /* OS/2 Doesn't Guarantee a Terminator */
511 if (strlen(msgbuf
) > 0) { /* If Non-Empty Msg, Trim CRLF */
512 char *lastc
= &msgbuf
[ strlen(msgbuf
)-1 ];
514 while (lastc
> msgbuf
&& isspace(Py_CHARMASK(*lastc
)))
515 *lastc
-- = '\0'; /* Trim Trailing Whitespace (CRLF) */
518 /* Add Optional Reason Text */
520 strcat(msgbuf
, " : ");
521 strcat(msgbuf
, reason
);
525 /**********************************************************************
526 * Decode an OS/2 Operating System Error Code
528 * A convenience function to lookup an OS/2 error code and return a
529 * text message we can use to raise a Python exception.
532 * The messages for errors returned from the OS/2 kernel reside in
533 * the file OSO001.MSG in the \OS2 directory hierarchy.
535 **********************************************************************/
537 os2_strerror(char *msgbuf
, int msgbuflen
, int errorcode
, char *reason
)
542 /* Retrieve Kernel-Related Error Message from OSO001.MSG File */
543 Py_BEGIN_ALLOW_THREADS
544 rc
= DosGetMessage(NULL
, 0, msgbuf
, msgbuflen
,
545 errorcode
, "oso001.msg", &msglen
);
549 os2_formatmsg(msgbuf
, msglen
, reason
);
551 PyOS_snprintf(msgbuf
, msgbuflen
,
552 "unknown OS error #%d", errorcode
);
557 /* Set an OS/2-specific error and return NULL. OS/2 kernel
558 errors are not in a global variable e.g. 'errno' nor are
559 they congruent with posix error numbers. */
561 static PyObject
* os2_error(int code
)
566 os2_strerror(text
, sizeof(text
), code
, "");
568 v
= Py_BuildValue("(is)", code
, text
);
570 PyErr_SetObject(PyExc_OSError
, v
);
573 return NULL
; /* Signal to Python that an Exception is Pending */
578 /* POSIX generic methods */
581 posix_fildes(PyObject
*fdobj
, int (*func
)(int))
585 fd
= PyObject_AsFileDescriptor(fdobj
);
588 Py_BEGIN_ALLOW_THREADS
592 return posix_error();
597 #ifdef Py_WIN_WIDE_FILENAMES
599 unicode_file_names(void)
601 static int canusewide
= -1;
602 if (canusewide
== -1) {
603 /* As per doc for ::GetVersion(), this is the correct test for
604 the Windows NT family. */
605 canusewide
= (GetVersion() < 0x80000000) ? 1 : 0;
612 posix_1str(PyObject
*args
, char *format
, int (*func
)(const char*))
616 if (!PyArg_ParseTuple(args
, format
,
617 Py_FileSystemDefaultEncoding
, &path1
))
619 Py_BEGIN_ALLOW_THREADS
620 res
= (*func
)(path1
);
623 return posix_error_with_allocated_filename(path1
);
630 posix_2str(PyObject
*args
,
632 int (*func
)(const char *, const char *))
634 char *path1
= NULL
, *path2
= NULL
;
636 if (!PyArg_ParseTuple(args
, format
,
637 Py_FileSystemDefaultEncoding
, &path1
,
638 Py_FileSystemDefaultEncoding
, &path2
))
640 Py_BEGIN_ALLOW_THREADS
641 res
= (*func
)(path1
, path2
);
646 /* XXX how to report both path1 and path2??? */
647 return posix_error();
652 #ifdef Py_WIN_WIDE_FILENAMES
654 win32_1str(PyObject
* args
, char* func
,
655 char* format
, BOOL (__stdcall
*funcA
)(LPCSTR
),
656 char* wformat
, BOOL (__stdcall
*funcW
)(LPWSTR
))
661 if (unicode_file_names()) {
662 if (!PyArg_ParseTuple(args
, wformat
, &uni
))
665 Py_BEGIN_ALLOW_THREADS
666 result
= funcW(PyUnicode_AsUnicode(uni
));
669 return win32_error_unicode(func
, PyUnicode_AsUnicode(uni
));
674 if (!PyArg_ParseTuple(args
, format
, &ansi
))
676 Py_BEGIN_ALLOW_THREADS
677 result
= funcA(ansi
);
680 return win32_error(func
, ansi
);
686 /* This is a reimplementation of the C library's chdir function,
687 but one that produces Win32 errors instead of DOS error codes.
688 chdir is essentially a wrapper around SetCurrentDirectory; however,
689 it also needs to set "magic" environment variables indicating
690 the per-drive current directory, which are of the form =<drive>: */
692 win32_chdir(LPCSTR path
)
694 char new_path
[MAX_PATH
+1];
698 if(!SetCurrentDirectoryA(path
))
700 result
= GetCurrentDirectoryA(MAX_PATH
+1, new_path
);
703 /* In the ANSI API, there should not be any paths longer
705 assert(result
<= MAX_PATH
+1);
706 if (strncmp(new_path
, "\\\\", 2) == 0 ||
707 strncmp(new_path
, "//", 2) == 0)
708 /* UNC path, nothing to do. */
710 env
[1] = new_path
[0];
711 return SetEnvironmentVariableA(env
, new_path
);
714 /* The Unicode version differs from the ANSI version
715 since the current directory might exceed MAX_PATH characters */
717 win32_wchdir(LPCWSTR path
)
719 wchar_t _new_path
[MAX_PATH
+1], *new_path
= _new_path
;
721 wchar_t env
[4] = L
"=x:";
723 if(!SetCurrentDirectoryW(path
))
725 result
= GetCurrentDirectoryW(MAX_PATH
+1, new_path
);
728 if (result
> MAX_PATH
+1) {
729 new_path
= malloc(result
);
731 SetLastError(ERROR_OUTOFMEMORY
);
735 if (wcsncmp(new_path
, L
"\\\\", 2) == 0 ||
736 wcsncmp(new_path
, L
"//", 2) == 0)
737 /* UNC path, nothing to do. */
739 env
[1] = new_path
[0];
740 result
= SetEnvironmentVariableW(env
, new_path
);
741 if (new_path
!= _new_path
)
748 /* The CRT of Windows has a number of flaws wrt. its stat() implementation:
749 - time stamps are restricted to second resolution
750 - file modification times suffer from forth-and-back conversions between
752 Therefore, we implement our own stat, based on the Win32 API directly.
754 #define HAVE_STAT_NSEC 1
759 unsigned short st_mode
;
773 static __int64 secs_between_epochs
= 11644473600; /* Seconds between 1.1.1601 and 1.1.1970 */
776 FILE_TIME_to_time_t_nsec(FILETIME
*in_ptr
, int *time_out
, int* nsec_out
)
778 /* XXX endianness. Shouldn't matter, as all Windows implementations are little-endian */
779 /* Cannot simply cast and dereference in_ptr,
780 since it might not be aligned properly */
782 memcpy(&in
, in_ptr
, sizeof(in
));
783 *nsec_out
= (int)(in
% 10000000) * 100; /* FILETIME is in units of 100 nsec. */
784 /* XXX Win32 supports time stamps past 2038; we currently don't */
785 *time_out
= Py_SAFE_DOWNCAST((in
/ 10000000) - secs_between_epochs
, __int64
, int);
789 time_t_to_FILE_TIME(int time_in
, int nsec_in
, FILETIME
*out_ptr
)
793 out
= time_in
+ secs_between_epochs
;
794 out
= out
* 10000000 + nsec_in
/ 100;
795 memcpy(out_ptr
, &out
, sizeof(out
));
798 /* Below, we *know* that ugo+r is 0444 */
800 #error Unsupported C library
803 attributes_to_mode(DWORD attr
)
806 if (attr
& FILE_ATTRIBUTE_DIRECTORY
)
807 m
|= _S_IFDIR
| 0111; /* IFEXEC for user,group,other */
810 if (attr
& FILE_ATTRIBUTE_READONLY
)
818 attribute_data_to_stat(WIN32_FILE_ATTRIBUTE_DATA
*info
, struct win32_stat
*result
)
820 memset(result
, 0, sizeof(*result
));
821 result
->st_mode
= attributes_to_mode(info
->dwFileAttributes
);
822 result
->st_size
= (((__int64
)info
->nFileSizeHigh
)<<32) + info
->nFileSizeLow
;
823 FILE_TIME_to_time_t_nsec(&info
->ftCreationTime
, &result
->st_ctime
, &result
->st_ctime_nsec
);
824 FILE_TIME_to_time_t_nsec(&info
->ftLastWriteTime
, &result
->st_mtime
, &result
->st_mtime_nsec
);
825 FILE_TIME_to_time_t_nsec(&info
->ftLastAccessTime
, &result
->st_atime
, &result
->st_atime_nsec
);
830 /* Emulate GetFileAttributesEx[AW] on Windows 95 */
831 static int checked
= 0;
832 static BOOL (CALLBACK
*gfaxa
)(LPCSTR
, GET_FILEEX_INFO_LEVELS
, LPVOID
);
833 static BOOL (CALLBACK
*gfaxw
)(LPCWSTR
, GET_FILEEX_INFO_LEVELS
, LPVOID
);
841 hKernel32
= GetModuleHandle("KERNEL32");
842 *(FARPROC
*)&gfaxa
= GetProcAddress(hKernel32
, "GetFileAttributesExA");
843 *(FARPROC
*)&gfaxw
= GetProcAddress(hKernel32
, "GetFileAttributesExW");
847 attributes_from_dir(LPCSTR pszFile
, LPWIN32_FILE_ATTRIBUTE_DATA pfad
)
850 WIN32_FIND_DATAA FileData
;
851 hFindFile
= FindFirstFileA(pszFile
, &FileData
);
852 if (hFindFile
== INVALID_HANDLE_VALUE
)
854 FindClose(hFindFile
);
855 pfad
->dwFileAttributes
= FileData
.dwFileAttributes
;
856 pfad
->ftCreationTime
= FileData
.ftCreationTime
;
857 pfad
->ftLastAccessTime
= FileData
.ftLastAccessTime
;
858 pfad
->ftLastWriteTime
= FileData
.ftLastWriteTime
;
859 pfad
->nFileSizeHigh
= FileData
.nFileSizeHigh
;
860 pfad
->nFileSizeLow
= FileData
.nFileSizeLow
;
865 attributes_from_dir_w(LPCWSTR pszFile
, LPWIN32_FILE_ATTRIBUTE_DATA pfad
)
868 WIN32_FIND_DATAW FileData
;
869 hFindFile
= FindFirstFileW(pszFile
, &FileData
);
870 if (hFindFile
== INVALID_HANDLE_VALUE
)
872 FindClose(hFindFile
);
873 pfad
->dwFileAttributes
= FileData
.dwFileAttributes
;
874 pfad
->ftCreationTime
= FileData
.ftCreationTime
;
875 pfad
->ftLastAccessTime
= FileData
.ftLastAccessTime
;
876 pfad
->ftLastWriteTime
= FileData
.ftLastWriteTime
;
877 pfad
->nFileSizeHigh
= FileData
.nFileSizeHigh
;
878 pfad
->nFileSizeLow
= FileData
.nFileSizeLow
;
883 Py_GetFileAttributesExA(LPCSTR pszFile
,
884 GET_FILEEX_INFO_LEVELS level
,
888 LPWIN32_FILE_ATTRIBUTE_DATA pfad
= pv
;
889 /* First try to use the system's implementation, if that is
890 available and either succeeds to gives an error other than
891 that it isn't implemented. */
894 result
= gfaxa(pszFile
, level
, pv
);
895 if (result
|| GetLastError() != ERROR_CALL_NOT_IMPLEMENTED
)
898 /* It's either not present, or not implemented.
899 Emulate using FindFirstFile. */
900 if (level
!= GetFileExInfoStandard
) {
901 SetLastError(ERROR_INVALID_PARAMETER
);
904 /* Use GetFileAttributes to validate that the file name
905 does not contain wildcards (which FindFirstFile would
907 if (GetFileAttributesA(pszFile
) == 0xFFFFFFFF)
909 return attributes_from_dir(pszFile
, pfad
);
913 Py_GetFileAttributesExW(LPCWSTR pszFile
,
914 GET_FILEEX_INFO_LEVELS level
,
918 LPWIN32_FILE_ATTRIBUTE_DATA pfad
= pv
;
919 /* First try to use the system's implementation, if that is
920 available and either succeeds to gives an error other than
921 that it isn't implemented. */
924 result
= gfaxw(pszFile
, level
, pv
);
925 if (result
|| GetLastError() != ERROR_CALL_NOT_IMPLEMENTED
)
928 /* It's either not present, or not implemented.
929 Emulate using FindFirstFile. */
930 if (level
!= GetFileExInfoStandard
) {
931 SetLastError(ERROR_INVALID_PARAMETER
);
934 /* Use GetFileAttributes to validate that the file name
935 does not contain wildcards (which FindFirstFile would
937 if (GetFileAttributesW(pszFile
) == 0xFFFFFFFF)
939 return attributes_from_dir_w(pszFile
, pfad
);
943 win32_stat(const char* path
, struct win32_stat
*result
)
945 WIN32_FILE_ATTRIBUTE_DATA info
;
948 /* XXX not supported on Win95 and NT 3.x */
949 if (!Py_GetFileAttributesExA(path
, GetFileExInfoStandard
, &info
)) {
950 if (GetLastError() != ERROR_SHARING_VIOLATION
) {
951 /* Protocol violation: we explicitly clear errno, instead of
952 setting it to a POSIX error. Callers should use GetLastError. */
956 /* Could not get attributes on open file. Fall back to
957 reading the directory. */
958 if (!attributes_from_dir(path
, &info
)) {
959 /* Very strange. This should not fail now */
965 code
= attribute_data_to_stat(&info
, result
);
968 /* Set S_IFEXEC if it is an .exe, .bat, ... */
969 dot
= strrchr(path
, '.');
971 if (stricmp(dot
, ".bat") == 0 ||
972 stricmp(dot
, ".cmd") == 0 ||
973 stricmp(dot
, ".exe") == 0 ||
974 stricmp(dot
, ".com") == 0)
975 result
->st_mode
|= 0111;
981 win32_wstat(const wchar_t* path
, struct win32_stat
*result
)
985 WIN32_FILE_ATTRIBUTE_DATA info
;
986 /* XXX not supported on Win95 and NT 3.x */
987 if (!Py_GetFileAttributesExW(path
, GetFileExInfoStandard
, &info
)) {
988 if (GetLastError() != ERROR_SHARING_VIOLATION
) {
989 /* Protocol violation: we explicitly clear errno, instead of
990 setting it to a POSIX error. Callers should use GetLastError. */
994 /* Could not get attributes on open file. Fall back to
995 reading the directory. */
996 if (!attributes_from_dir_w(path
, &info
)) {
997 /* Very strange. This should not fail now */
1003 code
= attribute_data_to_stat(&info
, result
);
1006 /* Set IFEXEC if it is an .exe, .bat, ... */
1007 dot
= wcsrchr(path
, '.');
1009 if (_wcsicmp(dot
, L
".bat") == 0 ||
1010 _wcsicmp(dot
, L
".cmd") == 0 ||
1011 _wcsicmp(dot
, L
".exe") == 0 ||
1012 _wcsicmp(dot
, L
".com") == 0)
1013 result
->st_mode
|= 0111;
1019 win32_fstat(int file_number
, struct win32_stat
*result
)
1021 BY_HANDLE_FILE_INFORMATION info
;
1025 h
= (HANDLE
)_get_osfhandle(file_number
);
1027 /* Protocol violation: we explicitly clear errno, instead of
1028 setting it to a POSIX error. Callers should use GetLastError. */
1031 if (h
== INVALID_HANDLE_VALUE
) {
1032 /* This is really a C library error (invalid file handle).
1033 We set the Win32 error to the closes one matching. */
1034 SetLastError(ERROR_INVALID_HANDLE
);
1037 memset(result
, 0, sizeof(*result
));
1039 type
= GetFileType(h
);
1040 if (type
== FILE_TYPE_UNKNOWN
) {
1041 DWORD error
= GetLastError();
1045 /* else: valid but unknown file */
1048 if (type
!= FILE_TYPE_DISK
) {
1049 if (type
== FILE_TYPE_CHAR
)
1050 result
->st_mode
= _S_IFCHR
;
1051 else if (type
== FILE_TYPE_PIPE
)
1052 result
->st_mode
= _S_IFIFO
;
1056 if (!GetFileInformationByHandle(h
, &info
)) {
1060 /* similar to stat() */
1061 result
->st_mode
= attributes_to_mode(info
.dwFileAttributes
);
1062 result
->st_size
= (((__int64
)info
.nFileSizeHigh
)<<32) + info
.nFileSizeLow
;
1063 FILE_TIME_to_time_t_nsec(&info
.ftCreationTime
, &result
->st_ctime
, &result
->st_ctime_nsec
);
1064 FILE_TIME_to_time_t_nsec(&info
.ftLastWriteTime
, &result
->st_mtime
, &result
->st_mtime_nsec
);
1065 FILE_TIME_to_time_t_nsec(&info
.ftLastAccessTime
, &result
->st_atime
, &result
->st_atime_nsec
);
1066 /* specific to fstat() */
1067 result
->st_nlink
= info
.nNumberOfLinks
;
1068 result
->st_ino
= (((__int64
)info
.nFileIndexHigh
)<<32) + info
.nFileIndexLow
;
1072 #endif /* MS_WINDOWS */
1074 PyDoc_STRVAR(stat_result__doc__
,
1075 "stat_result: Result from stat or lstat.\n\n\
1076 This object may be accessed either as a tuple of\n\
1077 (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\
1078 or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.\n\
1080 Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\
1081 or st_flags, they are available as attributes only.\n\
1083 See os.stat for more information.");
1085 static PyStructSequence_Field stat_result_fields
[] = {
1086 {"st_mode", "protection bits"},
1087 {"st_ino", "inode"},
1088 {"st_dev", "device"},
1089 {"st_nlink", "number of hard links"},
1090 {"st_uid", "user ID of owner"},
1091 {"st_gid", "group ID of owner"},
1092 {"st_size", "total size, in bytes"},
1093 /* The NULL is replaced with PyStructSequence_UnnamedField later. */
1094 {NULL
, "integer time of last access"},
1095 {NULL
, "integer time of last modification"},
1096 {NULL
, "integer time of last change"},
1097 {"st_atime", "time of last access"},
1098 {"st_mtime", "time of last modification"},
1099 {"st_ctime", "time of last change"},
1100 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1101 {"st_blksize", "blocksize for filesystem I/O"},
1103 #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
1104 {"st_blocks", "number of blocks allocated"},
1106 #ifdef HAVE_STRUCT_STAT_ST_RDEV
1107 {"st_rdev", "device type (if inode device)"},
1109 #ifdef HAVE_STRUCT_STAT_ST_FLAGS
1110 {"st_flags", "user defined flags for file"},
1112 #ifdef HAVE_STRUCT_STAT_ST_GEN
1113 {"st_gen", "generation number"},
1115 #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
1116 {"st_birthtime", "time of creation"},
1121 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1122 #define ST_BLKSIZE_IDX 13
1124 #define ST_BLKSIZE_IDX 12
1127 #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
1128 #define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1)
1130 #define ST_BLOCKS_IDX ST_BLKSIZE_IDX
1133 #ifdef HAVE_STRUCT_STAT_ST_RDEV
1134 #define ST_RDEV_IDX (ST_BLOCKS_IDX+1)
1136 #define ST_RDEV_IDX ST_BLOCKS_IDX
1139 #ifdef HAVE_STRUCT_STAT_ST_FLAGS
1140 #define ST_FLAGS_IDX (ST_RDEV_IDX+1)
1142 #define ST_FLAGS_IDX ST_RDEV_IDX
1145 #ifdef HAVE_STRUCT_STAT_ST_GEN
1146 #define ST_GEN_IDX (ST_FLAGS_IDX+1)
1148 #define ST_GEN_IDX ST_FLAGS_IDX
1151 #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
1152 #define ST_BIRTHTIME_IDX (ST_GEN_IDX+1)
1154 #define ST_BIRTHTIME_IDX ST_GEN_IDX
1157 static PyStructSequence_Desc stat_result_desc
= {
1158 "stat_result", /* name */
1159 stat_result__doc__
, /* doc */
1164 PyDoc_STRVAR(statvfs_result__doc__
,
1165 "statvfs_result: Result from statvfs or fstatvfs.\n\n\
1166 This object may be accessed either as a tuple of\n\
1167 (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\
1168 or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\
1170 See os.statvfs for more information.");
1172 static PyStructSequence_Field statvfs_result_fields
[] = {
1186 static PyStructSequence_Desc statvfs_result_desc
= {
1187 "statvfs_result", /* name */
1188 statvfs_result__doc__
, /* doc */
1189 statvfs_result_fields
,
1193 static int initialized
;
1194 static PyTypeObject StatResultType
;
1195 static PyTypeObject StatVFSResultType
;
1196 static newfunc structseq_new
;
1199 statresult_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
1201 PyStructSequence
*result
;
1204 result
= (PyStructSequence
*)structseq_new(type
, args
, kwds
);
1207 /* If we have been initialized from a tuple,
1208 st_?time might be set to None. Initialize it
1209 from the int slots. */
1210 for (i
= 7; i
<= 9; i
++) {
1211 if (result
->ob_item
[i
+3] == Py_None
) {
1213 Py_INCREF(result
->ob_item
[i
]);
1214 result
->ob_item
[i
+3] = result
->ob_item
[i
];
1217 return (PyObject
*)result
;
1222 /* If true, st_?time is float. */
1223 static int _stat_float_times
= 1;
1225 PyDoc_STRVAR(stat_float_times__doc__
,
1226 "stat_float_times([newval]) -> oldval\n\n\
1227 Determine whether os.[lf]stat represents time stamps as float objects.\n\
1228 If newval is True, future calls to stat() return floats, if it is False,\n\
1229 future calls return ints. \n\
1230 If newval is omitted, return the current setting.\n");
1233 stat_float_times(PyObject
* self
, PyObject
*args
)
1236 if (!PyArg_ParseTuple(args
, "|i:stat_float_times", &newval
))
1239 /* Return old value */
1240 return PyBool_FromLong(_stat_float_times
);
1241 _stat_float_times
= newval
;
1247 fill_time(PyObject
*v
, int index
, time_t sec
, unsigned long nsec
)
1249 PyObject
*fval
,*ival
;
1250 #if SIZEOF_TIME_T > SIZEOF_LONG
1251 ival
= PyLong_FromLongLong((PY_LONG_LONG
)sec
);
1253 ival
= PyInt_FromLong((long)sec
);
1257 if (_stat_float_times
) {
1258 fval
= PyFloat_FromDouble(sec
+ 1e-9*nsec
);
1263 PyStructSequence_SET_ITEM(v
, index
, ival
);
1264 PyStructSequence_SET_ITEM(v
, index
+3, fval
);
1267 /* pack a system stat C structure into the Python stat tuple
1268 (used by posix_stat() and posix_fstat()) */
1270 _pystat_fromstructstat(STRUCT_STAT
*st
)
1272 unsigned long ansec
, mnsec
, cnsec
;
1273 PyObject
*v
= PyStructSequence_New(&StatResultType
);
1277 PyStructSequence_SET_ITEM(v
, 0, PyInt_FromLong((long)st
->st_mode
));
1278 #ifdef HAVE_LARGEFILE_SUPPORT
1279 PyStructSequence_SET_ITEM(v
, 1,
1280 PyLong_FromLongLong((PY_LONG_LONG
)st
->st_ino
));
1282 PyStructSequence_SET_ITEM(v
, 1, PyInt_FromLong((long)st
->st_ino
));
1284 #if defined(HAVE_LONG_LONG) && !defined(MS_WINDOWS)
1285 PyStructSequence_SET_ITEM(v
, 2,
1286 PyLong_FromLongLong((PY_LONG_LONG
)st
->st_dev
));
1288 PyStructSequence_SET_ITEM(v
, 2, PyInt_FromLong((long)st
->st_dev
));
1290 PyStructSequence_SET_ITEM(v
, 3, PyInt_FromLong((long)st
->st_nlink
));
1291 PyStructSequence_SET_ITEM(v
, 4, PyInt_FromLong((long)st
->st_uid
));
1292 PyStructSequence_SET_ITEM(v
, 5, PyInt_FromLong((long)st
->st_gid
));
1293 #ifdef HAVE_LARGEFILE_SUPPORT
1294 PyStructSequence_SET_ITEM(v
, 6,
1295 PyLong_FromLongLong((PY_LONG_LONG
)st
->st_size
));
1297 PyStructSequence_SET_ITEM(v
, 6, PyInt_FromLong(st
->st_size
));
1300 #if defined(HAVE_STAT_TV_NSEC)
1301 ansec
= st
->st_atim
.tv_nsec
;
1302 mnsec
= st
->st_mtim
.tv_nsec
;
1303 cnsec
= st
->st_ctim
.tv_nsec
;
1304 #elif defined(HAVE_STAT_TV_NSEC2)
1305 ansec
= st
->st_atimespec
.tv_nsec
;
1306 mnsec
= st
->st_mtimespec
.tv_nsec
;
1307 cnsec
= st
->st_ctimespec
.tv_nsec
;
1308 #elif defined(HAVE_STAT_NSEC)
1309 ansec
= st
->st_atime_nsec
;
1310 mnsec
= st
->st_mtime_nsec
;
1311 cnsec
= st
->st_ctime_nsec
;
1313 ansec
= mnsec
= cnsec
= 0;
1315 fill_time(v
, 7, st
->st_atime
, ansec
);
1316 fill_time(v
, 8, st
->st_mtime
, mnsec
);
1317 fill_time(v
, 9, st
->st_ctime
, cnsec
);
1319 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1320 PyStructSequence_SET_ITEM(v
, ST_BLKSIZE_IDX
,
1321 PyInt_FromLong((long)st
->st_blksize
));
1323 #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
1324 PyStructSequence_SET_ITEM(v
, ST_BLOCKS_IDX
,
1325 PyInt_FromLong((long)st
->st_blocks
));
1327 #ifdef HAVE_STRUCT_STAT_ST_RDEV
1328 PyStructSequence_SET_ITEM(v
, ST_RDEV_IDX
,
1329 PyInt_FromLong((long)st
->st_rdev
));
1331 #ifdef HAVE_STRUCT_STAT_ST_GEN
1332 PyStructSequence_SET_ITEM(v
, ST_GEN_IDX
,
1333 PyInt_FromLong((long)st
->st_gen
));
1335 #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
1338 unsigned long bsec
,bnsec
;
1339 bsec
= (long)st
->st_birthtime
;
1340 #ifdef HAVE_STAT_TV_NSEC2
1341 bnsec
= st
->st_birthtimespec
.tv_nsec
;
1345 if (_stat_float_times
) {
1346 val
= PyFloat_FromDouble(bsec
+ 1e-9*bnsec
);
1348 val
= PyInt_FromLong((long)bsec
);
1350 PyStructSequence_SET_ITEM(v
, ST_BIRTHTIME_IDX
,
1354 #ifdef HAVE_STRUCT_STAT_ST_FLAGS
1355 PyStructSequence_SET_ITEM(v
, ST_FLAGS_IDX
,
1356 PyInt_FromLong((long)st
->st_flags
));
1359 if (PyErr_Occurred()) {
1369 /* IsUNCRoot -- test whether the supplied path is of the form \\SERVER\SHARE\,
1370 where / can be used in place of \ and the trailing slash is optional.
1371 Both SERVER and SHARE must have at least one character.
1374 #define ISSLASHA(c) ((c) == '\\' || (c) == '/')
1375 #define ISSLASHW(c) ((c) == L'\\' || (c) == L'/')
1377 #define ARRAYSIZE(a) (sizeof(a) / sizeof(a[0]))
1381 IsUNCRootA(char *path
, int pathlen
)
1383 #define ISSLASH ISSLASHA
1387 if (pathlen
< 5 || !ISSLASH(path
[0]) || !ISSLASH(path
[1]))
1388 /* minimum UNCRoot is \\x\y */
1390 for (i
= 2; i
< pathlen
; i
++)
1391 if (ISSLASH(path
[i
])) break;
1392 if (i
== 2 || i
== pathlen
)
1393 /* do not allow \\\SHARE or \\SERVER */
1396 for (i
= share
; i
< pathlen
; i
++)
1397 if (ISSLASH(path
[i
])) break;
1398 return (i
!= share
&& (i
== pathlen
|| i
== pathlen
-1));
1403 #ifdef Py_WIN_WIDE_FILENAMES
1405 IsUNCRootW(Py_UNICODE
*path
, int pathlen
)
1407 #define ISSLASH ISSLASHW
1411 if (pathlen
< 5 || !ISSLASH(path
[0]) || !ISSLASH(path
[1]))
1412 /* minimum UNCRoot is \\x\y */
1414 for (i
= 2; i
< pathlen
; i
++)
1415 if (ISSLASH(path
[i
])) break;
1416 if (i
== 2 || i
== pathlen
)
1417 /* do not allow \\\SHARE or \\SERVER */
1420 for (i
= share
; i
< pathlen
; i
++)
1421 if (ISSLASH(path
[i
])) break;
1422 return (i
!= share
&& (i
== pathlen
|| i
== pathlen
-1));
1426 #endif /* Py_WIN_WIDE_FILENAMES */
1427 #endif /* MS_WINDOWS */
1430 posix_do_stat(PyObject
*self
, PyObject
*args
,
1433 int (*statfunc
)(const char *, STRUCT_STAT
*, ...),
1435 int (*statfunc
)(const char *, STRUCT_STAT
*),
1438 int (*wstatfunc
)(const Py_UNICODE
*, STRUCT_STAT
*))
1441 char *path
= NULL
; /* pass this to stat; do not free() it */
1442 char *pathfree
= NULL
; /* this memory must be free'd */
1446 #ifdef Py_WIN_WIDE_FILENAMES
1447 /* If on wide-character-capable OS see if argument
1448 is Unicode and if so use wide API. */
1449 if (unicode_file_names()) {
1450 PyUnicodeObject
*po
;
1451 if (PyArg_ParseTuple(args
, wformat
, &po
)) {
1452 Py_UNICODE
*wpath
= PyUnicode_AS_UNICODE(po
);
1454 Py_BEGIN_ALLOW_THREADS
1455 /* PyUnicode_AS_UNICODE result OK without
1456 thread lock as it is a simple dereference. */
1457 res
= wstatfunc(wpath
, &st
);
1458 Py_END_ALLOW_THREADS
1461 return win32_error_unicode("stat", wpath
);
1462 return _pystat_fromstructstat(&st
);
1464 /* Drop the argument parsing error as narrow strings
1470 if (!PyArg_ParseTuple(args
, format
,
1471 Py_FileSystemDefaultEncoding
, &path
))
1475 Py_BEGIN_ALLOW_THREADS
1476 res
= (*statfunc
)(path
, &st
);
1477 Py_END_ALLOW_THREADS
1481 result
= win32_error("stat", pathfree
);
1483 result
= posix_error_with_filename(pathfree
);
1487 result
= _pystat_fromstructstat(&st
);
1489 PyMem_Free(pathfree
);
1495 PyDoc_STRVAR(posix_access__doc__
,
1496 "access(path, mode) -> True if granted, False otherwise\n\n\
1497 Use the real uid/gid to test for access to a path. Note that most\n\
1498 operations will use the effective uid/gid, therefore this routine can\n\
1499 be used in a suid/sgid environment to test if the invoking user has the\n\
1500 specified access to the path. The mode argument can be F_OK to test\n\
1501 existence, or the inclusive-OR of R_OK, W_OK, and X_OK.");
1504 posix_access(PyObject
*self
, PyObject
*args
)
1509 #ifdef Py_WIN_WIDE_FILENAMES
1511 if (unicode_file_names()) {
1512 PyUnicodeObject
*po
;
1513 if (PyArg_ParseTuple(args
, "Ui:access", &po
, &mode
)) {
1514 Py_BEGIN_ALLOW_THREADS
1515 /* PyUnicode_AS_UNICODE OK without thread lock as
1516 it is a simple dereference. */
1517 attr
= GetFileAttributesW(PyUnicode_AS_UNICODE(po
));
1518 Py_END_ALLOW_THREADS
1521 /* Drop the argument parsing error as narrow strings
1525 if (!PyArg_ParseTuple(args
, "eti:access",
1526 Py_FileSystemDefaultEncoding
, &path
, &mode
))
1528 Py_BEGIN_ALLOW_THREADS
1529 attr
= GetFileAttributesA(path
);
1530 Py_END_ALLOW_THREADS
1533 if (attr
== 0xFFFFFFFF)
1534 /* File does not exist, or cannot read attributes */
1535 return PyBool_FromLong(0);
1536 /* Access is possible if either write access wasn't requested, or
1537 the file isn't read-only. */
1538 return PyBool_FromLong(!(mode
& 2) || !(attr
& FILE_ATTRIBUTE_READONLY
));
1541 if (!PyArg_ParseTuple(args
, "eti:access",
1542 Py_FileSystemDefaultEncoding
, &path
, &mode
))
1544 Py_BEGIN_ALLOW_THREADS
1545 res
= access(path
, mode
);
1546 Py_END_ALLOW_THREADS
1548 return PyBool_FromLong(res
== 0);
1566 PyDoc_STRVAR(posix_ttyname__doc__
,
1567 "ttyname(fd) -> string\n\n\
1568 Return the name of the terminal device connected to 'fd'.");
1571 posix_ttyname(PyObject
*self
, PyObject
*args
)
1576 if (!PyArg_ParseTuple(args
, "i:ttyname", &id
))
1580 /* file descriptor 0 only, the default input device (stdin) */
1591 return posix_error();
1592 return PyString_FromString(ret
);
1597 PyDoc_STRVAR(posix_ctermid__doc__
,
1598 "ctermid() -> string\n\n\
1599 Return the name of the controlling terminal for this process.");
1602 posix_ctermid(PyObject
*self
, PyObject
*noargs
)
1605 char buffer
[L_ctermid
];
1607 #ifdef USE_CTERMID_R
1608 ret
= ctermid_r(buffer
);
1610 ret
= ctermid(buffer
);
1613 return posix_error();
1614 return PyString_FromString(buffer
);
1618 PyDoc_STRVAR(posix_chdir__doc__
,
1620 Change the current working directory to the specified path.");
1623 posix_chdir(PyObject
*self
, PyObject
*args
)
1626 return win32_1str(args
, "chdir", "s:chdir", win32_chdir
, "U:chdir", win32_wchdir
);
1627 #elif defined(PYOS_OS2) && defined(PYCC_GCC)
1628 return posix_1str(args
, "et:chdir", _chdir2
);
1629 #elif defined(__VMS)
1630 return posix_1str(args
, "et:chdir", (int (*)(const char *))chdir
);
1632 return posix_1str(args
, "et:chdir", chdir
);
1637 PyDoc_STRVAR(posix_fchdir__doc__
,
1638 "fchdir(fildes)\n\n\
1639 Change to the directory of the given file descriptor. fildes must be\n\
1640 opened on a directory, not a file.");
1643 posix_fchdir(PyObject
*self
, PyObject
*fdobj
)
1645 return posix_fildes(fdobj
, fchdir
);
1647 #endif /* HAVE_FCHDIR */
1650 PyDoc_STRVAR(posix_chmod__doc__
,
1651 "chmod(path, mode)\n\n\
1652 Change the access permissions of a file.");
1655 posix_chmod(PyObject
*self
, PyObject
*args
)
1660 #ifdef Py_WIN_WIDE_FILENAMES
1662 if (unicode_file_names()) {
1663 PyUnicodeObject
*po
;
1664 if (PyArg_ParseTuple(args
, "Ui|:chmod", &po
, &i
)) {
1665 Py_BEGIN_ALLOW_THREADS
1666 attr
= GetFileAttributesW(PyUnicode_AS_UNICODE(po
));
1667 if (attr
!= 0xFFFFFFFF) {
1669 attr
&= ~FILE_ATTRIBUTE_READONLY
;
1671 attr
|= FILE_ATTRIBUTE_READONLY
;
1672 res
= SetFileAttributesW(PyUnicode_AS_UNICODE(po
), attr
);
1676 Py_END_ALLOW_THREADS
1678 return win32_error_unicode("chmod",
1679 PyUnicode_AS_UNICODE(po
));
1683 /* Drop the argument parsing error as narrow strings
1687 if (!PyArg_ParseTuple(args
, "eti:chmod", Py_FileSystemDefaultEncoding
,
1690 Py_BEGIN_ALLOW_THREADS
1691 attr
= GetFileAttributesA(path
);
1692 if (attr
!= 0xFFFFFFFF) {
1694 attr
&= ~FILE_ATTRIBUTE_READONLY
;
1696 attr
|= FILE_ATTRIBUTE_READONLY
;
1697 res
= SetFileAttributesA(path
, attr
);
1701 Py_END_ALLOW_THREADS
1703 win32_error("chmod", path
);
1710 #else /* Py_WIN_WIDE_FILENAMES */
1711 if (!PyArg_ParseTuple(args
, "eti:chmod", Py_FileSystemDefaultEncoding
,
1714 Py_BEGIN_ALLOW_THREADS
1715 res
= chmod(path
, i
);
1716 Py_END_ALLOW_THREADS
1718 return posix_error_with_allocated_filename(path
);
1727 PyDoc_STRVAR(posix_chflags__doc__
,
1728 "chflags(path, flags)\n\n\
1732 posix_chflags(PyObject
*self
, PyObject
*args
)
1735 unsigned long flags
;
1737 if (!PyArg_ParseTuple(args
, "etk:chflags",
1738 Py_FileSystemDefaultEncoding
, &path
, &flags
))
1740 Py_BEGIN_ALLOW_THREADS
1741 res
= chflags(path
, flags
);
1742 Py_END_ALLOW_THREADS
1744 return posix_error_with_allocated_filename(path
);
1749 #endif /* HAVE_CHFLAGS */
1751 #ifdef HAVE_LCHFLAGS
1752 PyDoc_STRVAR(posix_lchflags__doc__
,
1753 "lchflags(path, flags)\n\n\
1755 This function will not follow symbolic links.");
1758 posix_lchflags(PyObject
*self
, PyObject
*args
)
1761 unsigned long flags
;
1763 if (!PyArg_ParseTuple(args
, "etk:lchflags",
1764 Py_FileSystemDefaultEncoding
, &path
, &flags
))
1766 Py_BEGIN_ALLOW_THREADS
1767 res
= lchflags(path
, flags
);
1768 Py_END_ALLOW_THREADS
1770 return posix_error_with_allocated_filename(path
);
1775 #endif /* HAVE_LCHFLAGS */
1778 PyDoc_STRVAR(posix_chroot__doc__
,
1780 Change root directory to path.");
1783 posix_chroot(PyObject
*self
, PyObject
*args
)
1785 return posix_1str(args
, "et:chroot", chroot
);
1790 PyDoc_STRVAR(posix_fsync__doc__
,
1792 force write of file with filedescriptor to disk.");
1795 posix_fsync(PyObject
*self
, PyObject
*fdobj
)
1797 return posix_fildes(fdobj
, fsync
);
1799 #endif /* HAVE_FSYNC */
1801 #ifdef HAVE_FDATASYNC
1804 extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */
1807 PyDoc_STRVAR(posix_fdatasync__doc__
,
1808 "fdatasync(fildes)\n\n\
1809 force write of file with filedescriptor to disk.\n\
1810 does not force update of metadata.");
1813 posix_fdatasync(PyObject
*self
, PyObject
*fdobj
)
1815 return posix_fildes(fdobj
, fdatasync
);
1817 #endif /* HAVE_FDATASYNC */
1821 PyDoc_STRVAR(posix_chown__doc__
,
1822 "chown(path, uid, gid)\n\n\
1823 Change the owner and group id of path to the numeric uid and gid.");
1826 posix_chown(PyObject
*self
, PyObject
*args
)
1831 if (!PyArg_ParseTuple(args
, "etii:chown",
1832 Py_FileSystemDefaultEncoding
, &path
,
1835 Py_BEGIN_ALLOW_THREADS
1836 res
= chown(path
, (uid_t
) uid
, (gid_t
) gid
);
1837 Py_END_ALLOW_THREADS
1839 return posix_error_with_allocated_filename(path
);
1844 #endif /* HAVE_CHOWN */
1847 PyDoc_STRVAR(posix_lchown__doc__
,
1848 "lchown(path, uid, gid)\n\n\
1849 Change the owner and group id of path to the numeric uid and gid.\n\
1850 This function will not follow symbolic links.");
1853 posix_lchown(PyObject
*self
, PyObject
*args
)
1858 if (!PyArg_ParseTuple(args
, "etii:lchown",
1859 Py_FileSystemDefaultEncoding
, &path
,
1862 Py_BEGIN_ALLOW_THREADS
1863 res
= lchown(path
, (uid_t
) uid
, (gid_t
) gid
);
1864 Py_END_ALLOW_THREADS
1866 return posix_error_with_allocated_filename(path
);
1871 #endif /* HAVE_LCHOWN */
1875 PyDoc_STRVAR(posix_getcwd__doc__
,
1876 "getcwd() -> path\n\n\
1877 Return a string representing the current working directory.");
1880 posix_getcwd(PyObject
*self
, PyObject
*noargs
)
1885 Py_BEGIN_ALLOW_THREADS
1886 #if defined(PYOS_OS2) && defined(PYCC_GCC)
1887 res
= _getcwd2(buf
, sizeof buf
);
1889 res
= getcwd(buf
, sizeof buf
);
1891 Py_END_ALLOW_THREADS
1893 return posix_error();
1894 return PyString_FromString(buf
);
1897 #ifdef Py_USING_UNICODE
1898 PyDoc_STRVAR(posix_getcwdu__doc__
,
1899 "getcwdu() -> path\n\n\
1900 Return a unicode string representing the current working directory.");
1903 posix_getcwdu(PyObject
*self
, PyObject
*noargs
)
1908 #ifdef Py_WIN_WIDE_FILENAMES
1910 if (unicode_file_names()) {
1912 wchar_t *wbuf2
= wbuf
;
1914 Py_BEGIN_ALLOW_THREADS
1915 len
= GetCurrentDirectoryW(sizeof wbuf
/ sizeof wbuf
[0], wbuf
);
1916 /* If the buffer is large enough, len does not include the
1917 terminating \0. If the buffer is too small, len includes
1918 the space needed for the terminator. */
1919 if (len
>= sizeof wbuf
/ sizeof wbuf
[0]) {
1920 wbuf2
= malloc(len
* sizeof(wchar_t));
1922 len
= GetCurrentDirectoryW(len
, wbuf2
);
1924 Py_END_ALLOW_THREADS
1930 if (wbuf2
!= wbuf
) free(wbuf2
);
1931 return win32_error("getcwdu", NULL
);
1933 resobj
= PyUnicode_FromWideChar(wbuf2
, len
);
1934 if (wbuf2
!= wbuf
) free(wbuf2
);
1939 Py_BEGIN_ALLOW_THREADS
1940 #if defined(PYOS_OS2) && defined(PYCC_GCC)
1941 res
= _getcwd2(buf
, sizeof buf
);
1943 res
= getcwd(buf
, sizeof buf
);
1945 Py_END_ALLOW_THREADS
1947 return posix_error();
1948 return PyUnicode_Decode(buf
, strlen(buf
), Py_FileSystemDefaultEncoding
,"strict");
1955 PyDoc_STRVAR(posix_link__doc__
,
1956 "link(src, dst)\n\n\
1957 Create a hard link to a file.");
1960 posix_link(PyObject
*self
, PyObject
*args
)
1962 return posix_2str(args
, "etet:link", link
);
1964 #endif /* HAVE_LINK */
1967 PyDoc_STRVAR(posix_listdir__doc__
,
1968 "listdir(path) -> list_of_strings\n\n\
1969 Return a list containing the names of the entries in the directory.\n\
1971 path: path of directory to list\n\
1973 The list is in arbitrary order. It does not include the special\n\
1974 entries '.' and '..' even if they are present in the directory.");
1977 posix_listdir(PyObject
*self
, PyObject
*args
)
1979 /* XXX Should redo this putting the (now four) versions of opendir
1980 in separate files instead of having them all here... */
1981 #if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
1986 WIN32_FIND_DATA FileData
;
1987 char namebuf
[MAX_PATH
+5]; /* Overallocate for \\*.*\0 */
1988 char *bufptr
= namebuf
;
1989 Py_ssize_t len
= sizeof(namebuf
)-5; /* only claim to have space for MAX_PATH */
1991 #ifdef Py_WIN_WIDE_FILENAMES
1992 /* If on wide-character-capable OS see if argument
1993 is Unicode and if so use wide API. */
1994 if (unicode_file_names()) {
1996 if (PyArg_ParseTuple(args
, "U:listdir", &po
)) {
1997 WIN32_FIND_DATAW wFileData
;
1998 Py_UNICODE
*wnamebuf
;
2000 /* Overallocate for \\*.*\0 */
2001 len
= PyUnicode_GET_SIZE(po
);
2002 wnamebuf
= malloc((len
+ 5) * sizeof(wchar_t));
2007 wcscpy(wnamebuf
, PyUnicode_AS_UNICODE(po
));
2008 wch
= len
> 0 ? wnamebuf
[len
-1] : '\0';
2009 if (wch
!= L
'/' && wch
!= L
'\\' && wch
!= L
':')
2010 wnamebuf
[len
++] = L
'\\';
2011 wcscpy(wnamebuf
+ len
, L
"*.*");
2012 if ((d
= PyList_New(0)) == NULL
) {
2016 hFindFile
= FindFirstFileW(wnamebuf
, &wFileData
);
2017 if (hFindFile
== INVALID_HANDLE_VALUE
) {
2018 int error
= GetLastError();
2019 if (error
== ERROR_FILE_NOT_FOUND
) {
2024 win32_error_unicode("FindFirstFileW", wnamebuf
);
2029 /* Skip over . and .. */
2030 if (wcscmp(wFileData
.cFileName
, L
".") != 0 &&
2031 wcscmp(wFileData
.cFileName
, L
"..") != 0) {
2032 v
= PyUnicode_FromUnicode(wFileData
.cFileName
, wcslen(wFileData
.cFileName
));
2038 if (PyList_Append(d
, v
) != 0) {
2046 Py_BEGIN_ALLOW_THREADS
2047 result
= FindNextFileW(hFindFile
, &wFileData
);
2048 Py_END_ALLOW_THREADS
2049 /* FindNextFile sets error to ERROR_NO_MORE_FILES if
2050 it got to the end of the directory. */
2051 if (!result
&& GetLastError() != ERROR_NO_MORE_FILES
) {
2053 win32_error_unicode("FindNextFileW", wnamebuf
);
2054 FindClose(hFindFile
);
2058 } while (result
== TRUE
);
2060 if (FindClose(hFindFile
) == FALSE
) {
2062 win32_error_unicode("FindClose", wnamebuf
);
2069 /* Drop the argument parsing error as narrow strings
2075 if (!PyArg_ParseTuple(args
, "et#:listdir",
2076 Py_FileSystemDefaultEncoding
, &bufptr
, &len
))
2079 char ch
= namebuf
[len
-1];
2080 if (ch
!= SEP
&& ch
!= ALTSEP
&& ch
!= ':')
2081 namebuf
[len
++] = '/';
2083 strcpy(namebuf
+ len
, "*.*");
2085 if ((d
= PyList_New(0)) == NULL
)
2088 hFindFile
= FindFirstFile(namebuf
, &FileData
);
2089 if (hFindFile
== INVALID_HANDLE_VALUE
) {
2090 int error
= GetLastError();
2091 if (error
== ERROR_FILE_NOT_FOUND
)
2094 return win32_error("FindFirstFile", namebuf
);
2097 /* Skip over . and .. */
2098 if (strcmp(FileData
.cFileName
, ".") != 0 &&
2099 strcmp(FileData
.cFileName
, "..") != 0) {
2100 v
= PyString_FromString(FileData
.cFileName
);
2106 if (PyList_Append(d
, v
) != 0) {
2114 Py_BEGIN_ALLOW_THREADS
2115 result
= FindNextFile(hFindFile
, &FileData
);
2116 Py_END_ALLOW_THREADS
2117 /* FindNextFile sets error to ERROR_NO_MORE_FILES if
2118 it got to the end of the directory. */
2119 if (!result
&& GetLastError() != ERROR_NO_MORE_FILES
) {
2121 win32_error("FindNextFile", namebuf
);
2122 FindClose(hFindFile
);
2125 } while (result
== TRUE
);
2127 if (FindClose(hFindFile
) == FALSE
) {
2129 return win32_error("FindClose", namebuf
);
2134 #elif defined(PYOS_OS2)
2137 #define MAX_PATH CCHMAXPATH
2142 char namebuf
[MAX_PATH
+5];
2148 if (!PyArg_ParseTuple(args
, "t#:listdir", &name
, &len
))
2150 if (len
>= MAX_PATH
) {
2151 PyErr_SetString(PyExc_ValueError
, "path too long");
2154 strcpy(namebuf
, name
);
2155 for (pt
= namebuf
; *pt
; pt
++)
2158 if (namebuf
[len
-1] != SEP
)
2159 namebuf
[len
++] = SEP
;
2160 strcpy(namebuf
+ len
, "*.*");
2162 if ((d
= PyList_New(0)) == NULL
)
2165 rc
= DosFindFirst(namebuf
, /* Wildcard Pattern to Match */
2166 &hdir
, /* Handle to Use While Search Directory */
2167 FILE_READONLY
| FILE_HIDDEN
| FILE_SYSTEM
| FILE_DIRECTORY
,
2168 &ep
, sizeof(ep
), /* Structure to Receive Directory Entry */
2169 &srchcnt
, /* Max and Actual Count of Entries Per Iteration */
2170 FIL_STANDARD
); /* Format of Entry (EAs or Not) */
2172 if (rc
!= NO_ERROR
) {
2174 return posix_error_with_filename(name
);
2177 if (srchcnt
> 0) { /* If Directory is NOT Totally Empty, */
2179 if (ep
.achName
[0] == '.'
2180 && (ep
.achName
[1] == '\0' || (ep
.achName
[1] == '.' && ep
.achName
[2] == '\0')))
2181 continue; /* Skip Over "." and ".." Names */
2183 strcpy(namebuf
, ep
.achName
);
2185 /* Leave Case of Name Alone -- In Native Form */
2186 /* (Removed Forced Lowercasing Code) */
2188 v
= PyString_FromString(namebuf
);
2194 if (PyList_Append(d
, v
) != 0) {
2201 } while (DosFindNext(hdir
, &ep
, sizeof(ep
), &srchcnt
) == NO_ERROR
&& srchcnt
> 0);
2211 int arg_is_unicode
= 1;
2214 if (!PyArg_ParseTuple(args
, "U:listdir", &v
)) {
2218 if (!PyArg_ParseTuple(args
, "et:listdir", Py_FileSystemDefaultEncoding
, &name
))
2220 if ((dirp
= opendir(name
)) == NULL
) {
2221 return posix_error_with_allocated_filename(name
);
2223 if ((d
= PyList_New(0)) == NULL
) {
2229 Py_BEGIN_ALLOW_THREADS
2231 Py_END_ALLOW_THREADS
2234 if (ep
->d_name
[0] == '.' &&
2236 (ep
->d_name
[1] == '.' && NAMLEN(ep
) == 2)))
2238 v
= PyString_FromStringAndSize(ep
->d_name
, NAMLEN(ep
));
2244 #ifdef Py_USING_UNICODE
2245 if (arg_is_unicode
) {
2248 w
= PyUnicode_FromEncodedObject(v
,
2249 Py_FileSystemDefaultEncoding
,
2256 /* fall back to the original byte string, as
2257 discussed in patch #683592 */
2262 if (PyList_Append(d
, v
) != 0) {
2270 if (errno
!= 0 && d
!= NULL
) {
2271 /* readdir() returned NULL and set errno */
2274 return posix_error_with_allocated_filename(name
);
2281 #endif /* which OS */
2282 } /* end of posix_listdir */
2285 /* A helper function for abspath on win32 */
2287 posix__getfullpathname(PyObject
*self
, PyObject
*args
)
2289 /* assume encoded strings wont more than double no of chars */
2290 char inbuf
[MAX_PATH
*2];
2291 char *inbufp
= inbuf
;
2292 Py_ssize_t insize
= sizeof(inbuf
);
2293 char outbuf
[MAX_PATH
*2];
2295 #ifdef Py_WIN_WIDE_FILENAMES
2296 if (unicode_file_names()) {
2297 PyUnicodeObject
*po
;
2298 if (PyArg_ParseTuple(args
, "U|:_getfullpathname", &po
)) {
2299 Py_UNICODE woutbuf
[MAX_PATH
*2];
2301 if (!GetFullPathNameW(PyUnicode_AS_UNICODE(po
),
2302 sizeof(woutbuf
)/sizeof(woutbuf
[0]),
2304 return win32_error("GetFullPathName", "");
2305 return PyUnicode_FromUnicode(woutbuf
, wcslen(woutbuf
));
2307 /* Drop the argument parsing error as narrow strings
2312 if (!PyArg_ParseTuple (args
, "et#:_getfullpathname",
2313 Py_FileSystemDefaultEncoding
, &inbufp
,
2316 if (!GetFullPathName(inbuf
, sizeof(outbuf
)/sizeof(outbuf
[0]),
2318 return win32_error("GetFullPathName", inbuf
);
2319 if (PyUnicode_Check(PyTuple_GetItem(args
, 0))) {
2320 return PyUnicode_Decode(outbuf
, strlen(outbuf
),
2321 Py_FileSystemDefaultEncoding
, NULL
);
2323 return PyString_FromString(outbuf
);
2324 } /* end of posix__getfullpathname */
2325 #endif /* MS_WINDOWS */
2327 PyDoc_STRVAR(posix_mkdir__doc__
,
2328 "mkdir(path [, mode=0777])\n\n\
2329 Create a directory.");
2332 posix_mkdir(PyObject
*self
, PyObject
*args
)
2338 #ifdef Py_WIN_WIDE_FILENAMES
2339 if (unicode_file_names()) {
2340 PyUnicodeObject
*po
;
2341 if (PyArg_ParseTuple(args
, "U|i:mkdir", &po
, &mode
)) {
2342 Py_BEGIN_ALLOW_THREADS
2343 /* PyUnicode_AS_UNICODE OK without thread lock as
2344 it is a simple dereference. */
2345 res
= CreateDirectoryW(PyUnicode_AS_UNICODE(po
), NULL
);
2346 Py_END_ALLOW_THREADS
2348 return win32_error_unicode("mkdir", PyUnicode_AS_UNICODE(po
));
2352 /* Drop the argument parsing error as narrow strings
2356 if (!PyArg_ParseTuple(args
, "et|i:mkdir",
2357 Py_FileSystemDefaultEncoding
, &path
, &mode
))
2359 Py_BEGIN_ALLOW_THREADS
2360 /* PyUnicode_AS_UNICODE OK without thread lock as
2361 it is a simple dereference. */
2362 res
= CreateDirectoryA(path
, NULL
);
2363 Py_END_ALLOW_THREADS
2365 win32_error("mkdir", path
);
2374 if (!PyArg_ParseTuple(args
, "et|i:mkdir",
2375 Py_FileSystemDefaultEncoding
, &path
, &mode
))
2377 Py_BEGIN_ALLOW_THREADS
2378 #if ( defined(__WATCOMC__) || defined(PYCC_VACPP) ) && !defined(__QNX__)
2381 res
= mkdir(path
, mode
);
2383 Py_END_ALLOW_THREADS
2385 return posix_error_with_allocated_filename(path
);
2393 /* sys/resource.h is needed for at least: wait3(), wait4(), broken nice. */
2394 #if defined(HAVE_SYS_RESOURCE_H)
2395 #include <sys/resource.h>
2400 PyDoc_STRVAR(posix_nice__doc__
,
2401 "nice(inc) -> new_priority\n\n\
2402 Decrease the priority of process by inc and return the new priority.");
2405 posix_nice(PyObject
*self
, PyObject
*args
)
2407 int increment
, value
;
2409 if (!PyArg_ParseTuple(args
, "i:nice", &increment
))
2412 /* There are two flavours of 'nice': one that returns the new
2413 priority (as required by almost all standards out there) and the
2414 Linux/FreeBSD/BSDI one, which returns '0' on success and advices
2415 the use of getpriority() to get the new priority.
2417 If we are of the nice family that returns the new priority, we
2418 need to clear errno before the call, and check if errno is filled
2419 before calling posix_error() on a returnvalue of -1, because the
2420 -1 may be the actual new priority! */
2423 value
= nice(increment
);
2424 #if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY)
2426 value
= getpriority(PRIO_PROCESS
, 0);
2428 if (value
== -1 && errno
!= 0)
2429 /* either nice() or getpriority() returned an error */
2430 return posix_error();
2431 return PyInt_FromLong((long) value
);
2433 #endif /* HAVE_NICE */
2435 PyDoc_STRVAR(posix_rename__doc__
,
2436 "rename(old, new)\n\n\
2437 Rename a file or directory.");
2440 posix_rename(PyObject
*self
, PyObject
*args
)
2446 if (unicode_file_names()) {
2447 if (!PyArg_ParseTuple(args
, "O&O&:rename",
2448 convert_to_unicode
, &o1
,
2449 convert_to_unicode
, &o2
))
2452 Py_BEGIN_ALLOW_THREADS
2453 result
= MoveFileW(PyUnicode_AsUnicode(o1
),
2454 PyUnicode_AsUnicode(o2
));
2455 Py_END_ALLOW_THREADS
2459 return win32_error("rename", NULL
);
2464 if (!PyArg_ParseTuple(args
, "ss:rename", &p1
, &p2
))
2466 Py_BEGIN_ALLOW_THREADS
2467 result
= MoveFileA(p1
, p2
);
2468 Py_END_ALLOW_THREADS
2470 return win32_error("rename", NULL
);
2474 return posix_2str(args
, "etet:rename", rename
);
2479 PyDoc_STRVAR(posix_rmdir__doc__
,
2481 Remove a directory.");
2484 posix_rmdir(PyObject
*self
, PyObject
*args
)
2487 return win32_1str(args
, "rmdir", "s:rmdir", RemoveDirectoryA
, "U:rmdir", RemoveDirectoryW
);
2489 return posix_1str(args
, "et:rmdir", rmdir
);
2494 PyDoc_STRVAR(posix_stat__doc__
,
2495 "stat(path) -> stat result\n\n\
2496 Perform a stat system call on the given path.");
2499 posix_stat(PyObject
*self
, PyObject
*args
)
2502 return posix_do_stat(self
, args
, "et:stat", STAT
, "U:stat", win32_wstat
);
2504 return posix_do_stat(self
, args
, "et:stat", STAT
, NULL
, NULL
);
2510 PyDoc_STRVAR(posix_system__doc__
,
2511 "system(command) -> exit_status\n\n\
2512 Execute the command (a string) in a subshell.");
2515 posix_system(PyObject
*self
, PyObject
*args
)
2519 if (!PyArg_ParseTuple(args
, "s:system", &command
))
2521 Py_BEGIN_ALLOW_THREADS
2522 sts
= system(command
);
2523 Py_END_ALLOW_THREADS
2524 return PyInt_FromLong(sts
);
2529 PyDoc_STRVAR(posix_umask__doc__
,
2530 "umask(new_mask) -> old_mask\n\n\
2531 Set the current numeric umask and return the previous umask.");
2534 posix_umask(PyObject
*self
, PyObject
*args
)
2537 if (!PyArg_ParseTuple(args
, "i:umask", &i
))
2541 return posix_error();
2542 return PyInt_FromLong((long)i
);
2546 PyDoc_STRVAR(posix_unlink__doc__
,
2548 Remove a file (same as remove(path)).");
2550 PyDoc_STRVAR(posix_remove__doc__
,
2552 Remove a file (same as unlink(path)).");
2555 posix_unlink(PyObject
*self
, PyObject
*args
)
2558 return win32_1str(args
, "remove", "s:remove", DeleteFileA
, "U:remove", DeleteFileW
);
2560 return posix_1str(args
, "et:remove", unlink
);
2566 PyDoc_STRVAR(posix_uname__doc__
,
2567 "uname() -> (sysname, nodename, release, version, machine)\n\n\
2568 Return a tuple identifying the current operating system.");
2571 posix_uname(PyObject
*self
, PyObject
*noargs
)
2576 Py_BEGIN_ALLOW_THREADS
2578 Py_END_ALLOW_THREADS
2580 return posix_error();
2581 return Py_BuildValue("(sssss)",
2588 #endif /* HAVE_UNAME */
2591 extract_time(PyObject
*t
, long* sec
, long* usec
)
2594 if (PyFloat_Check(t
)) {
2595 double tval
= PyFloat_AsDouble(t
);
2596 PyObject
*intobj
= Py_Type(t
)->tp_as_number
->nb_int(t
);
2599 intval
= PyInt_AsLong(intobj
);
2601 if (intval
== -1 && PyErr_Occurred())
2604 *usec
= (long)((tval
- intval
) * 1e6
); /* can't exceed 1000000 */
2606 /* If rounding gave us a negative number,
2611 intval
= PyInt_AsLong(t
);
2612 if (intval
== -1 && PyErr_Occurred())
2619 PyDoc_STRVAR(posix_utime__doc__
,
2620 "utime(path, (atime, mtime))\n\
2621 utime(path, None)\n\n\
2622 Set the access and modified time of the file to the given values. If the\n\
2623 second form is used, set the access and modified times to the current time.");
2626 posix_utime(PyObject
*self
, PyObject
*args
)
2628 #ifdef Py_WIN_WIDE_FILENAMES
2630 PyUnicodeObject
*obwpath
;
2631 wchar_t *wpath
= NULL
;
2634 long atimesec
, mtimesec
, ausec
, musec
;
2635 FILETIME atime
, mtime
;
2636 PyObject
*result
= NULL
;
2638 if (unicode_file_names()) {
2639 if (PyArg_ParseTuple(args
, "UO|:utime", &obwpath
, &arg
)) {
2640 wpath
= PyUnicode_AS_UNICODE(obwpath
);
2641 Py_BEGIN_ALLOW_THREADS
2642 hFile
= CreateFileW(wpath
, FILE_WRITE_ATTRIBUTES
, 0,
2643 NULL
, OPEN_EXISTING
,
2644 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
2645 Py_END_ALLOW_THREADS
2646 if (hFile
== INVALID_HANDLE_VALUE
)
2647 return win32_error_unicode("utime", wpath
);
2649 /* Drop the argument parsing error as narrow strings
2654 if (!PyArg_ParseTuple(args
, "etO:utime",
2655 Py_FileSystemDefaultEncoding
, &apath
, &arg
))
2657 Py_BEGIN_ALLOW_THREADS
2658 hFile
= CreateFileA(apath
, FILE_WRITE_ATTRIBUTES
, 0,
2659 NULL
, OPEN_EXISTING
,
2660 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
2661 Py_END_ALLOW_THREADS
2662 if (hFile
== INVALID_HANDLE_VALUE
) {
2663 win32_error("utime", apath
);
2670 if (arg
== Py_None
) {
2672 GetSystemTime(&now
);
2673 if (!SystemTimeToFileTime(&now
, &mtime
) ||
2674 !SystemTimeToFileTime(&now
, &atime
)) {
2675 win32_error("utime", NULL
);
2679 else if (!PyTuple_Check(arg
) || PyTuple_Size(arg
) != 2) {
2680 PyErr_SetString(PyExc_TypeError
,
2681 "utime() arg 2 must be a tuple (atime, mtime)");
2685 if (extract_time(PyTuple_GET_ITEM(arg
, 0),
2686 &atimesec
, &ausec
) == -1)
2688 time_t_to_FILE_TIME(atimesec
, 1000*ausec
, &atime
);
2689 if (extract_time(PyTuple_GET_ITEM(arg
, 1),
2690 &mtimesec
, &musec
) == -1)
2692 time_t_to_FILE_TIME(mtimesec
, 1000*musec
, &mtime
);
2694 if (!SetFileTime(hFile
, NULL
, &atime
, &mtime
)) {
2695 /* Avoid putting the file name into the error here,
2696 as that may confuse the user into believing that
2697 something is wrong with the file, when it also
2698 could be the time stamp that gives a problem. */
2699 win32_error("utime", NULL
);
2706 #else /* Py_WIN_WIDE_FILENAMES */
2709 long atime
, mtime
, ausec
, musec
;
2713 #if defined(HAVE_UTIMES)
2714 struct timeval buf
[2];
2715 #define ATIME buf[0].tv_sec
2716 #define MTIME buf[1].tv_sec
2717 #elif defined(HAVE_UTIME_H)
2718 /* XXX should define struct utimbuf instead, above */
2720 #define ATIME buf.actime
2721 #define MTIME buf.modtime
2722 #define UTIME_ARG &buf
2723 #else /* HAVE_UTIMES */
2725 #define ATIME buf[0]
2726 #define MTIME buf[1]
2727 #define UTIME_ARG buf
2728 #endif /* HAVE_UTIMES */
2731 if (!PyArg_ParseTuple(args
, "etO:utime",
2732 Py_FileSystemDefaultEncoding
, &path
, &arg
))
2734 if (arg
== Py_None
) {
2735 /* optional time values not given */
2736 Py_BEGIN_ALLOW_THREADS
2737 res
= utime(path
, NULL
);
2738 Py_END_ALLOW_THREADS
2740 else if (!PyTuple_Check(arg
) || PyTuple_Size(arg
) != 2) {
2741 PyErr_SetString(PyExc_TypeError
,
2742 "utime() arg 2 must be a tuple (atime, mtime)");
2747 if (extract_time(PyTuple_GET_ITEM(arg
, 0),
2748 &atime
, &ausec
) == -1) {
2752 if (extract_time(PyTuple_GET_ITEM(arg
, 1),
2753 &mtime
, &musec
) == -1) {
2760 buf
[0].tv_usec
= ausec
;
2761 buf
[1].tv_usec
= musec
;
2762 Py_BEGIN_ALLOW_THREADS
2763 res
= utimes(path
, buf
);
2764 Py_END_ALLOW_THREADS
2766 Py_BEGIN_ALLOW_THREADS
2767 res
= utime(path
, UTIME_ARG
);
2768 Py_END_ALLOW_THREADS
2769 #endif /* HAVE_UTIMES */
2772 return posix_error_with_allocated_filename(path
);
2780 #endif /* Py_WIN_WIDE_FILENAMES */
2784 /* Process operations */
2786 PyDoc_STRVAR(posix__exit__doc__
,
2788 Exit to the system with specified status, without normal exit processing.");
2791 posix__exit(PyObject
*self
, PyObject
*args
)
2794 if (!PyArg_ParseTuple(args
, "i:_exit", &sts
))
2797 return NULL
; /* Make gcc -Wall happy */
2800 #if defined(HAVE_EXECV) || defined(HAVE_SPAWNV)
2802 free_string_array(char **array
, Py_ssize_t count
)
2805 for (i
= 0; i
< count
; i
++)
2806 PyMem_Free(array
[i
]);
2813 PyDoc_STRVAR(posix_execv__doc__
,
2814 "execv(path, args)\n\n\
2815 Execute an executable path with arguments, replacing current process.\n\
2817 path: path of executable file\n\
2818 args: tuple or list of strings");
2821 posix_execv(PyObject
*self
, PyObject
*args
)
2827 PyObject
*(*getitem
)(PyObject
*, Py_ssize_t
);
2829 /* execv has two arguments: (path, argv), where
2830 argv is a list or tuple of strings. */
2832 if (!PyArg_ParseTuple(args
, "etO:execv",
2833 Py_FileSystemDefaultEncoding
,
2836 if (PyList_Check(argv
)) {
2837 argc
= PyList_Size(argv
);
2838 getitem
= PyList_GetItem
;
2840 else if (PyTuple_Check(argv
)) {
2841 argc
= PyTuple_Size(argv
);
2842 getitem
= PyTuple_GetItem
;
2845 PyErr_SetString(PyExc_TypeError
, "execv() arg 2 must be a tuple or list");
2850 argvlist
= PyMem_NEW(char *, argc
+1);
2851 if (argvlist
== NULL
) {
2853 return PyErr_NoMemory();
2855 for (i
= 0; i
< argc
; i
++) {
2856 if (!PyArg_Parse((*getitem
)(argv
, i
), "et",
2857 Py_FileSystemDefaultEncoding
,
2859 free_string_array(argvlist
, i
);
2860 PyErr_SetString(PyExc_TypeError
,
2861 "execv() arg 2 must contain only strings");
2867 argvlist
[argc
] = NULL
;
2869 execv(path
, argvlist
);
2871 /* If we get here it's definitely an error */
2873 free_string_array(argvlist
, argc
);
2875 return posix_error();
2879 PyDoc_STRVAR(posix_execve__doc__
,
2880 "execve(path, args, env)\n\n\
2881 Execute a path with arguments and environment, replacing current process.\n\
2883 path: path of executable file\n\
2884 args: tuple or list of arguments\n\
2885 env: dictionary of strings mapping to strings");
2888 posix_execve(PyObject
*self
, PyObject
*args
)
2891 PyObject
*argv
, *env
;
2894 PyObject
*key
, *val
, *keys
=NULL
, *vals
=NULL
;
2895 Py_ssize_t i
, pos
, argc
, envc
;
2896 PyObject
*(*getitem
)(PyObject
*, Py_ssize_t
);
2897 Py_ssize_t lastarg
= 0;
2899 /* execve has three arguments: (path, argv, env), where
2900 argv is a list or tuple of strings and env is a dictionary
2901 like posix.environ. */
2903 if (!PyArg_ParseTuple(args
, "etOO:execve",
2904 Py_FileSystemDefaultEncoding
,
2905 &path
, &argv
, &env
))
2907 if (PyList_Check(argv
)) {
2908 argc
= PyList_Size(argv
);
2909 getitem
= PyList_GetItem
;
2911 else if (PyTuple_Check(argv
)) {
2912 argc
= PyTuple_Size(argv
);
2913 getitem
= PyTuple_GetItem
;
2916 PyErr_SetString(PyExc_TypeError
,
2917 "execve() arg 2 must be a tuple or list");
2920 if (!PyMapping_Check(env
)) {
2921 PyErr_SetString(PyExc_TypeError
,
2922 "execve() arg 3 must be a mapping object");
2926 argvlist
= PyMem_NEW(char *, argc
+1);
2927 if (argvlist
== NULL
) {
2931 for (i
= 0; i
< argc
; i
++) {
2932 if (!PyArg_Parse((*getitem
)(argv
, i
),
2933 "et;execve() arg 2 must contain only strings",
2934 Py_FileSystemDefaultEncoding
,
2942 argvlist
[argc
] = NULL
;
2944 i
= PyMapping_Size(env
);
2947 envlist
= PyMem_NEW(char *, i
+ 1);
2948 if (envlist
== NULL
) {
2953 keys
= PyMapping_Keys(env
);
2954 vals
= PyMapping_Values(env
);
2957 if (!PyList_Check(keys
) || !PyList_Check(vals
)) {
2958 PyErr_SetString(PyExc_TypeError
,
2959 "execve(): env.keys() or env.values() is not a list");
2963 for (pos
= 0; pos
< i
; pos
++) {
2967 key
= PyList_GetItem(keys
, pos
);
2968 val
= PyList_GetItem(vals
, pos
);
2974 "s;execve() arg 3 contains a non-string key",
2978 "s;execve() arg 3 contains a non-string value",
2984 #if defined(PYOS_OS2)
2985 /* Omit Pseudo-Env Vars that Would Confuse Programs if Passed On */
2986 if (stricmp(k
, "BEGINLIBPATH") != 0 && stricmp(k
, "ENDLIBPATH") != 0) {
2988 len
= PyString_Size(key
) + PyString_Size(val
) + 2;
2989 p
= PyMem_NEW(char, len
);
2994 PyOS_snprintf(p
, len
, "%s=%s", k
, v
);
2995 envlist
[envc
++] = p
;
2996 #if defined(PYOS_OS2)
3002 execve(path
, argvlist
, envlist
);
3004 /* If we get here it's definitely an error */
3006 (void) posix_error();
3010 PyMem_DEL(envlist
[envc
]);
3013 free_string_array(argvlist
, lastarg
);
3020 #endif /* HAVE_EXECV */
3024 PyDoc_STRVAR(posix_spawnv__doc__
,
3025 "spawnv(mode, path, args)\n\n\
3026 Execute the program 'path' in a new process.\n\
3028 mode: mode of process creation\n\
3029 path: path of executable file\n\
3030 args: tuple or list of strings");
3033 posix_spawnv(PyObject
*self
, PyObject
*args
)
3040 Py_intptr_t spawnval
;
3041 PyObject
*(*getitem
)(PyObject
*, Py_ssize_t
);
3043 /* spawnv has three arguments: (mode, path, argv), where
3044 argv is a list or tuple of strings. */
3046 if (!PyArg_ParseTuple(args
, "ietO:spawnv", &mode
,
3047 Py_FileSystemDefaultEncoding
,
3050 if (PyList_Check(argv
)) {
3051 argc
= PyList_Size(argv
);
3052 getitem
= PyList_GetItem
;
3054 else if (PyTuple_Check(argv
)) {
3055 argc
= PyTuple_Size(argv
);
3056 getitem
= PyTuple_GetItem
;
3059 PyErr_SetString(PyExc_TypeError
,
3060 "spawnv() arg 2 must be a tuple or list");
3065 argvlist
= PyMem_NEW(char *, argc
+1);
3066 if (argvlist
== NULL
) {
3068 return PyErr_NoMemory();
3070 for (i
= 0; i
< argc
; i
++) {
3071 if (!PyArg_Parse((*getitem
)(argv
, i
), "et",
3072 Py_FileSystemDefaultEncoding
,
3074 free_string_array(argvlist
, i
);
3077 "spawnv() arg 2 must contain only strings");
3082 argvlist
[argc
] = NULL
;
3084 #if defined(PYOS_OS2) && defined(PYCC_GCC)
3085 Py_BEGIN_ALLOW_THREADS
3086 spawnval
= spawnv(mode
, path
, argvlist
);
3087 Py_END_ALLOW_THREADS
3089 if (mode
== _OLD_P_OVERLAY
)
3092 Py_BEGIN_ALLOW_THREADS
3093 spawnval
= _spawnv(mode
, path
, argvlist
);
3094 Py_END_ALLOW_THREADS
3097 free_string_array(argvlist
, argc
);
3101 return posix_error();
3103 #if SIZEOF_LONG == SIZEOF_VOID_P
3104 return Py_BuildValue("l", (long) spawnval
);
3106 return Py_BuildValue("L", (PY_LONG_LONG
) spawnval
);
3111 PyDoc_STRVAR(posix_spawnve__doc__
,
3112 "spawnve(mode, path, args, env)\n\n\
3113 Execute the program 'path' in a new process.\n\
3115 mode: mode of process creation\n\
3116 path: path of executable file\n\
3117 args: tuple or list of arguments\n\
3118 env: dictionary of strings mapping to strings");
3121 posix_spawnve(PyObject
*self
, PyObject
*args
)
3124 PyObject
*argv
, *env
;
3127 PyObject
*key
, *val
, *keys
=NULL
, *vals
=NULL
, *res
=NULL
;
3128 int mode
, pos
, envc
;
3130 Py_intptr_t spawnval
;
3131 PyObject
*(*getitem
)(PyObject
*, Py_ssize_t
);
3132 Py_ssize_t lastarg
= 0;
3134 /* spawnve has four arguments: (mode, path, argv, env), where
3135 argv is a list or tuple of strings and env is a dictionary
3136 like posix.environ. */
3138 if (!PyArg_ParseTuple(args
, "ietOO:spawnve", &mode
,
3139 Py_FileSystemDefaultEncoding
,
3140 &path
, &argv
, &env
))
3142 if (PyList_Check(argv
)) {
3143 argc
= PyList_Size(argv
);
3144 getitem
= PyList_GetItem
;
3146 else if (PyTuple_Check(argv
)) {
3147 argc
= PyTuple_Size(argv
);
3148 getitem
= PyTuple_GetItem
;
3151 PyErr_SetString(PyExc_TypeError
,
3152 "spawnve() arg 2 must be a tuple or list");
3155 if (!PyMapping_Check(env
)) {
3156 PyErr_SetString(PyExc_TypeError
,
3157 "spawnve() arg 3 must be a mapping object");
3161 argvlist
= PyMem_NEW(char *, argc
+1);
3162 if (argvlist
== NULL
) {
3166 for (i
= 0; i
< argc
; i
++) {
3167 if (!PyArg_Parse((*getitem
)(argv
, i
),
3168 "et;spawnve() arg 2 must contain only strings",
3169 Py_FileSystemDefaultEncoding
,
3177 argvlist
[argc
] = NULL
;
3179 i
= PyMapping_Size(env
);
3182 envlist
= PyMem_NEW(char *, i
+ 1);
3183 if (envlist
== NULL
) {
3188 keys
= PyMapping_Keys(env
);
3189 vals
= PyMapping_Values(env
);
3192 if (!PyList_Check(keys
) || !PyList_Check(vals
)) {
3193 PyErr_SetString(PyExc_TypeError
,
3194 "spawnve(): env.keys() or env.values() is not a list");
3198 for (pos
= 0; pos
< i
; pos
++) {
3202 key
= PyList_GetItem(keys
, pos
);
3203 val
= PyList_GetItem(vals
, pos
);
3209 "s;spawnve() arg 3 contains a non-string key",
3213 "s;spawnve() arg 3 contains a non-string value",
3218 len
= PyString_Size(key
) + PyString_Size(val
) + 2;
3219 p
= PyMem_NEW(char, len
);
3224 PyOS_snprintf(p
, len
, "%s=%s", k
, v
);
3225 envlist
[envc
++] = p
;
3229 #if defined(PYOS_OS2) && defined(PYCC_GCC)
3230 Py_BEGIN_ALLOW_THREADS
3231 spawnval
= spawnve(mode
, path
, argvlist
, envlist
);
3232 Py_END_ALLOW_THREADS
3234 if (mode
== _OLD_P_OVERLAY
)
3237 Py_BEGIN_ALLOW_THREADS
3238 spawnval
= _spawnve(mode
, path
, argvlist
, envlist
);
3239 Py_END_ALLOW_THREADS
3243 (void) posix_error();
3245 #if SIZEOF_LONG == SIZEOF_VOID_P
3246 res
= Py_BuildValue("l", (long) spawnval
);
3248 res
= Py_BuildValue("L", (PY_LONG_LONG
) spawnval
);
3253 PyMem_DEL(envlist
[envc
]);
3256 free_string_array(argvlist
, lastarg
);
3264 /* OS/2 supports spawnvp & spawnvpe natively */
3265 #if defined(PYOS_OS2)
3266 PyDoc_STRVAR(posix_spawnvp__doc__
,
3267 "spawnvp(mode, file, args)\n\n\
3268 Execute the program 'file' in a new process, using the environment\n\
3269 search path to find the file.\n\
3271 mode: mode of process creation\n\
3272 file: executable file name\n\
3273 args: tuple or list of strings");
3276 posix_spawnvp(PyObject
*self
, PyObject
*args
)
3282 Py_intptr_t spawnval
;
3283 PyObject
*(*getitem
)(PyObject
*, Py_ssize_t
);
3285 /* spawnvp has three arguments: (mode, path, argv), where
3286 argv is a list or tuple of strings. */
3288 if (!PyArg_ParseTuple(args
, "ietO:spawnvp", &mode
,
3289 Py_FileSystemDefaultEncoding
,
3292 if (PyList_Check(argv
)) {
3293 argc
= PyList_Size(argv
);
3294 getitem
= PyList_GetItem
;
3296 else if (PyTuple_Check(argv
)) {
3297 argc
= PyTuple_Size(argv
);
3298 getitem
= PyTuple_GetItem
;
3301 PyErr_SetString(PyExc_TypeError
,
3302 "spawnvp() arg 2 must be a tuple or list");
3307 argvlist
= PyMem_NEW(char *, argc
+1);
3308 if (argvlist
== NULL
) {
3310 return PyErr_NoMemory();
3312 for (i
= 0; i
< argc
; i
++) {
3313 if (!PyArg_Parse((*getitem
)(argv
, i
), "et",
3314 Py_FileSystemDefaultEncoding
,
3316 free_string_array(argvlist
, i
);
3319 "spawnvp() arg 2 must contain only strings");
3324 argvlist
[argc
] = NULL
;
3326 Py_BEGIN_ALLOW_THREADS
3327 #if defined(PYCC_GCC)
3328 spawnval
= spawnvp(mode
, path
, argvlist
);
3330 spawnval
= _spawnvp(mode
, path
, argvlist
);
3332 Py_END_ALLOW_THREADS
3334 free_string_array(argvlist
, argc
);
3338 return posix_error();
3340 return Py_BuildValue("l", (long) spawnval
);
3344 PyDoc_STRVAR(posix_spawnvpe__doc__
,
3345 "spawnvpe(mode, file, args, env)\n\n\
3346 Execute the program 'file' in a new process, using the environment\n\
3347 search path to find the file.\n\
3349 mode: mode of process creation\n\
3350 file: executable file name\n\
3351 args: tuple or list of arguments\n\
3352 env: dictionary of strings mapping to strings");
3355 posix_spawnvpe(PyObject
*self
, PyObject
*args
)
3358 PyObject
*argv
, *env
;
3361 PyObject
*key
, *val
, *keys
=NULL
, *vals
=NULL
, *res
=NULL
;
3362 int mode
, i
, pos
, argc
, envc
;
3363 Py_intptr_t spawnval
;
3364 PyObject
*(*getitem
)(PyObject
*, Py_ssize_t
);
3367 /* spawnvpe has four arguments: (mode, path, argv, env), where
3368 argv is a list or tuple of strings and env is a dictionary
3369 like posix.environ. */
3371 if (!PyArg_ParseTuple(args
, "ietOO:spawnvpe", &mode
,
3372 Py_FileSystemDefaultEncoding
,
3373 &path
, &argv
, &env
))
3375 if (PyList_Check(argv
)) {
3376 argc
= PyList_Size(argv
);
3377 getitem
= PyList_GetItem
;
3379 else if (PyTuple_Check(argv
)) {
3380 argc
= PyTuple_Size(argv
);
3381 getitem
= PyTuple_GetItem
;
3384 PyErr_SetString(PyExc_TypeError
,
3385 "spawnvpe() arg 2 must be a tuple or list");
3388 if (!PyMapping_Check(env
)) {
3389 PyErr_SetString(PyExc_TypeError
,
3390 "spawnvpe() arg 3 must be a mapping object");
3394 argvlist
= PyMem_NEW(char *, argc
+1);
3395 if (argvlist
== NULL
) {
3399 for (i
= 0; i
< argc
; i
++) {
3400 if (!PyArg_Parse((*getitem
)(argv
, i
),
3401 "et;spawnvpe() arg 2 must contain only strings",
3402 Py_FileSystemDefaultEncoding
,
3410 argvlist
[argc
] = NULL
;
3412 i
= PyMapping_Size(env
);
3415 envlist
= PyMem_NEW(char *, i
+ 1);
3416 if (envlist
== NULL
) {
3421 keys
= PyMapping_Keys(env
);
3422 vals
= PyMapping_Values(env
);
3425 if (!PyList_Check(keys
) || !PyList_Check(vals
)) {
3426 PyErr_SetString(PyExc_TypeError
,
3427 "spawnvpe(): env.keys() or env.values() is not a list");
3431 for (pos
= 0; pos
< i
; pos
++) {
3435 key
= PyList_GetItem(keys
, pos
);
3436 val
= PyList_GetItem(vals
, pos
);
3442 "s;spawnvpe() arg 3 contains a non-string key",
3446 "s;spawnvpe() arg 3 contains a non-string value",
3451 len
= PyString_Size(key
) + PyString_Size(val
) + 2;
3452 p
= PyMem_NEW(char, len
);
3457 PyOS_snprintf(p
, len
, "%s=%s", k
, v
);
3458 envlist
[envc
++] = p
;
3462 Py_BEGIN_ALLOW_THREADS
3463 #if defined(PYCC_GCC)
3464 spawnval
= spawnve(mode
, path
, argvlist
, envlist
);
3466 spawnval
= _spawnve(mode
, path
, argvlist
, envlist
);
3468 Py_END_ALLOW_THREADS
3471 (void) posix_error();
3473 res
= Py_BuildValue("l", (long) spawnval
);
3477 PyMem_DEL(envlist
[envc
]);
3480 free_string_array(argvlist
, lastarg
);
3487 #endif /* PYOS_OS2 */
3488 #endif /* HAVE_SPAWNV */
3492 PyDoc_STRVAR(posix_fork1__doc__
,
3493 "fork1() -> pid\n\n\
3494 Fork a child process with a single multiplexed (i.e., not bound) thread.\n\
3496 Return 0 to child process and PID of child to parent process.");
3499 posix_fork1(PyObject
*self
, PyObject
*noargs
)
3503 return posix_error();
3505 return PyInt_FromLong((long)pid
);
3511 PyDoc_STRVAR(posix_fork__doc__
,
3513 Fork a child process.\n\
3514 Return 0 to child process and PID of child to parent process.");
3517 posix_fork(PyObject
*self
, PyObject
*noargs
)
3521 return posix_error();
3524 return PyInt_FromLong((long)pid
);
3528 /* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */
3529 /* IRIX has both /dev/ptc and /dev/ptmx, use ptmx */
3530 #if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX)
3531 #define DEV_PTY_FILE "/dev/ptc"
3532 #define HAVE_DEV_PTMX
3534 #define DEV_PTY_FILE "/dev/ptmx"
3537 #if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX)
3541 #ifdef HAVE_LIBUTIL_H
3542 #include <libutil.h>
3543 #endif /* HAVE_LIBUTIL_H */
3544 #endif /* HAVE_PTY_H */
3545 #ifdef HAVE_STROPTS_H
3546 #include <stropts.h>
3548 #endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX */
3550 #if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
3551 PyDoc_STRVAR(posix_openpty__doc__
,
3552 "openpty() -> (master_fd, slave_fd)\n\n\
3553 Open a pseudo-terminal, returning open fd's for both master and slave end.\n");
3556 posix_openpty(PyObject
*self
, PyObject
*noargs
)
3558 int master_fd
, slave_fd
;
3559 #ifndef HAVE_OPENPTY
3562 #if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
3563 PyOS_sighandler_t sig_saved
;
3565 extern char *ptsname(int fildes
);
3570 if (openpty(&master_fd
, &slave_fd
, NULL
, NULL
, NULL
) != 0)
3571 return posix_error();
3572 #elif defined(HAVE__GETPTY)
3573 slave_name
= _getpty(&master_fd
, O_RDWR
, 0666, 0);
3574 if (slave_name
== NULL
)
3575 return posix_error();
3577 slave_fd
= open(slave_name
, O_RDWR
);
3579 return posix_error();
3581 master_fd
= open(DEV_PTY_FILE
, O_RDWR
| O_NOCTTY
); /* open master */
3583 return posix_error();
3584 sig_saved
= PyOS_setsig(SIGCHLD
, SIG_DFL
);
3585 /* change permission of slave */
3586 if (grantpt(master_fd
) < 0) {
3587 PyOS_setsig(SIGCHLD
, sig_saved
);
3588 return posix_error();
3591 if (unlockpt(master_fd
) < 0) {
3592 PyOS_setsig(SIGCHLD
, sig_saved
);
3593 return posix_error();
3595 PyOS_setsig(SIGCHLD
, sig_saved
);
3596 slave_name
= ptsname(master_fd
); /* get name of slave */
3597 if (slave_name
== NULL
)
3598 return posix_error();
3599 slave_fd
= open(slave_name
, O_RDWR
| O_NOCTTY
); /* open slave */
3601 return posix_error();
3602 #if !defined(__CYGWIN__) && !defined(HAVE_DEV_PTC)
3603 ioctl(slave_fd
, I_PUSH
, "ptem"); /* push ptem */
3604 ioctl(slave_fd
, I_PUSH
, "ldterm"); /* push ldterm */
3606 ioctl(slave_fd
, I_PUSH
, "ttcompat"); /* push ttcompat */
3608 #endif /* HAVE_CYGWIN */
3609 #endif /* HAVE_OPENPTY */
3611 return Py_BuildValue("(ii)", master_fd
, slave_fd
);
3614 #endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */
3617 PyDoc_STRVAR(posix_forkpty__doc__
,
3618 "forkpty() -> (pid, master_fd)\n\n\
3619 Fork a new process with a new pseudo-terminal as controlling tty.\n\n\
3620 Like fork(), return 0 as pid to child process, and PID of child to parent.\n\
3621 To both, return fd of newly opened pseudo-terminal.\n");
3624 posix_forkpty(PyObject
*self
, PyObject
*noargs
)
3626 int master_fd
= -1, pid
;
3628 pid
= forkpty(&master_fd
, NULL
, NULL
, NULL
);
3630 return posix_error();
3633 return Py_BuildValue("(ii)", pid
, master_fd
);
3638 PyDoc_STRVAR(posix_getegid__doc__
,
3639 "getegid() -> egid\n\n\
3640 Return the current process's effective group id.");
3643 posix_getegid(PyObject
*self
, PyObject
*noargs
)
3645 return PyInt_FromLong((long)getegid());
3651 PyDoc_STRVAR(posix_geteuid__doc__
,
3652 "geteuid() -> euid\n\n\
3653 Return the current process's effective user id.");
3656 posix_geteuid(PyObject
*self
, PyObject
*noargs
)
3658 return PyInt_FromLong((long)geteuid());
3664 PyDoc_STRVAR(posix_getgid__doc__
,
3665 "getgid() -> gid\n\n\
3666 Return the current process's group id.");
3669 posix_getgid(PyObject
*self
, PyObject
*noargs
)
3671 return PyInt_FromLong((long)getgid());
3676 PyDoc_STRVAR(posix_getpid__doc__
,
3677 "getpid() -> pid\n\n\
3678 Return the current process id");
3681 posix_getpid(PyObject
*self
, PyObject
*noargs
)
3683 return PyInt_FromLong((long)getpid());
3687 #ifdef HAVE_GETGROUPS
3688 PyDoc_STRVAR(posix_getgroups__doc__
,
3689 "getgroups() -> list of group IDs\n\n\
3690 Return list of supplemental group IDs for the process.");
3693 posix_getgroups(PyObject
*self
, PyObject
*noargs
)
3695 PyObject
*result
= NULL
;
3698 #define MAX_GROUPS NGROUPS_MAX
3700 /* defined to be 16 on Solaris7, so this should be a small number */
3701 #define MAX_GROUPS 64
3703 gid_t grouplist
[MAX_GROUPS
];
3706 n
= getgroups(MAX_GROUPS
, grouplist
);
3710 result
= PyList_New(n
);
3711 if (result
!= NULL
) {
3713 for (i
= 0; i
< n
; ++i
) {
3714 PyObject
*o
= PyInt_FromLong((long)grouplist
[i
]);
3720 PyList_SET_ITEM(result
, i
, o
);
3730 PyDoc_STRVAR(posix_getpgid__doc__
,
3731 "getpgid(pid) -> pgid\n\n\
3732 Call the system call getpgid().");
3735 posix_getpgid(PyObject
*self
, PyObject
*args
)
3738 if (!PyArg_ParseTuple(args
, "i:getpgid", &pid
))
3740 pgid
= getpgid(pid
);
3742 return posix_error();
3743 return PyInt_FromLong((long)pgid
);
3745 #endif /* HAVE_GETPGID */
3749 PyDoc_STRVAR(posix_getpgrp__doc__
,
3750 "getpgrp() -> pgrp\n\n\
3751 Return the current process group id.");
3754 posix_getpgrp(PyObject
*self
, PyObject
*noargs
)
3756 #ifdef GETPGRP_HAVE_ARG
3757 return PyInt_FromLong((long)getpgrp(0));
3758 #else /* GETPGRP_HAVE_ARG */
3759 return PyInt_FromLong((long)getpgrp());
3760 #endif /* GETPGRP_HAVE_ARG */
3762 #endif /* HAVE_GETPGRP */
3766 PyDoc_STRVAR(posix_setpgrp__doc__
,
3768 Make this process a session leader.");
3771 posix_setpgrp(PyObject
*self
, PyObject
*noargs
)
3773 #ifdef SETPGRP_HAVE_ARG
3774 if (setpgrp(0, 0) < 0)
3775 #else /* SETPGRP_HAVE_ARG */
3777 #endif /* SETPGRP_HAVE_ARG */
3778 return posix_error();
3783 #endif /* HAVE_SETPGRP */
3786 PyDoc_STRVAR(posix_getppid__doc__
,
3787 "getppid() -> ppid\n\n\
3788 Return the parent's process id.");
3791 posix_getppid(PyObject
*self
, PyObject
*noargs
)
3793 return PyInt_FromLong((long)getppid());
3798 #ifdef HAVE_GETLOGIN
3799 PyDoc_STRVAR(posix_getlogin__doc__
,
3800 "getlogin() -> string\n\n\
3801 Return the actual login name.");
3804 posix_getlogin(PyObject
*self
, PyObject
*noargs
)
3806 PyObject
*result
= NULL
;
3808 int old_errno
= errno
;
3816 PyErr_SetString(PyExc_OSError
,
3817 "unable to determine login name");
3820 result
= PyString_FromString(name
);
3828 PyDoc_STRVAR(posix_getuid__doc__
,
3829 "getuid() -> uid\n\n\
3830 Return the current process's user id.");
3833 posix_getuid(PyObject
*self
, PyObject
*noargs
)
3835 return PyInt_FromLong((long)getuid());
3841 PyDoc_STRVAR(posix_kill__doc__
,
3842 "kill(pid, sig)\n\n\
3843 Kill a process with a signal.");
3846 posix_kill(PyObject
*self
, PyObject
*args
)
3849 if (!PyArg_ParseTuple(args
, "ii:kill", &pid
, &sig
))
3851 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
3852 if (sig
== XCPT_SIGNAL_INTR
|| sig
== XCPT_SIGNAL_BREAK
) {
3854 if ((rc
= DosSendSignalException(pid
, sig
)) != NO_ERROR
)
3855 return os2_error(rc
);
3857 } else if (sig
== XCPT_SIGNAL_KILLPROC
) {
3859 if ((rc
= DosKillProcess(DKP_PROCESS
, pid
)) != NO_ERROR
)
3860 return os2_error(rc
);
3863 return NULL
; /* Unrecognized Signal Requested */
3865 if (kill(pid
, sig
) == -1)
3866 return posix_error();
3874 PyDoc_STRVAR(posix_killpg__doc__
,
3875 "killpg(pgid, sig)\n\n\
3876 Kill a process group with a signal.");
3879 posix_killpg(PyObject
*self
, PyObject
*args
)
3882 if (!PyArg_ParseTuple(args
, "ii:killpg", &pgid
, &sig
))
3884 if (killpg(pgid
, sig
) == -1)
3885 return posix_error();
3893 #ifdef HAVE_SYS_LOCK_H
3894 #include <sys/lock.h>
3897 PyDoc_STRVAR(posix_plock__doc__
,
3899 Lock program segments into memory.");
3902 posix_plock(PyObject
*self
, PyObject
*args
)
3905 if (!PyArg_ParseTuple(args
, "i:plock", &op
))
3907 if (plock(op
) == -1)
3908 return posix_error();
3916 PyDoc_STRVAR(posix_popen__doc__
,
3917 "popen(command [, mode='r' [, bufsize]]) -> pipe\n\n\
3918 Open a pipe to/from a command returning a file object.");
3920 #if defined(PYOS_OS2)
3921 #if defined(PYCC_VACPP)
3923 async_system(const char *command
)
3925 char errormsg
[256], args
[1024];
3929 char *shell
= getenv("COMSPEC");
3933 /* avoid overflowing the argument buffer */
3934 if (strlen(shell
) + 3 + strlen(command
) >= 1024)
3935 return ERROR_NOT_ENOUGH_MEMORY
3938 strcat(args
, shell
);
3939 strcat(args
, "/c ");
3940 strcat(args
, command
);
3942 /* execute asynchronously, inheriting the environment */
3943 rc
= DosExecPgm(errormsg
,
3954 popen(const char *command
, const char *mode
, int pipesize
, int *err
)
3960 /* mode determines which of stdin or stdout is reconnected to
3961 * the pipe to the child
3963 if (strchr(mode
, 'r') != NULL
) {
3964 tgt_fd
= 1; /* stdout */
3965 } else if (strchr(mode
, 'w')) {
3966 tgt_fd
= 0; /* stdin */
3968 *err
= ERROR_INVALID_ACCESS
;
3972 /* setup the pipe */
3973 if ((rc
= DosCreatePipe(&pipeh
[0], &pipeh
[1], pipesize
)) != NO_ERROR
) {
3978 /* prevent other threads accessing stdio */
3981 /* reconnect stdio and execute child */
3984 if (dup2(pipeh
[tgtfd
], tgtfd
) == 0) {
3985 DosClose(pipeh
[tgtfd
]);
3986 rc
= async_system(command
);
3993 /* allow other threads access to stdio */
3996 /* if execution of child was successful return file stream */
3998 return fdopen(pipeh
[1 - tgtfd
], mode
);
4000 DosClose(pipeh
[1 - tgtfd
]);
4007 posix_popen(PyObject
*self
, PyObject
*args
)
4011 int err
, bufsize
= -1;
4014 if (!PyArg_ParseTuple(args
, "s|si:popen", &name
, &mode
, &bufsize
))
4016 Py_BEGIN_ALLOW_THREADS
4017 fp
= popen(name
, mode
, (bufsize
> 0) ? bufsize
: 4096, &err
);
4018 Py_END_ALLOW_THREADS
4020 return os2_error(err
);
4022 f
= PyFile_FromFile(fp
, name
, mode
, fclose
);
4024 PyFile_SetBufSize(f
, bufsize
);
4028 #elif defined(PYCC_GCC)
4030 /* standard posix version of popen() support */
4032 posix_popen(PyObject
*self
, PyObject
*args
)
4039 if (!PyArg_ParseTuple(args
, "s|si:popen", &name
, &mode
, &bufsize
))
4041 Py_BEGIN_ALLOW_THREADS
4042 fp
= popen(name
, mode
);
4043 Py_END_ALLOW_THREADS
4045 return posix_error();
4046 f
= PyFile_FromFile(fp
, name
, mode
, pclose
);
4048 PyFile_SetBufSize(f
, bufsize
);
4052 /* fork() under OS/2 has lots'o'warts
4053 * EMX supports pipe() and spawn*() so we can synthesize popen[234]()
4054 * most of this code is a ripoff of the win32 code, but using the
4055 * capabilities of EMX's C library routines
4058 /* These tell _PyPopen() whether to return 1, 2, or 3 file objects. */
4064 static PyObject
*_PyPopen(char *, int, int, int);
4065 static int _PyPclose(FILE *file
);
4068 * Internal dictionary mapping popen* file pointers to process handles,
4069 * for use when retrieving the process exit code. See _PyPclose() below
4070 * for more information on this dictionary's use.
4072 static PyObject
*_PyPopenProcs
= NULL
;
4074 /* os2emx version of popen2()
4076 * The result of this function is a pipe (file) connected to the
4077 * process's stdin, and a pipe connected to the process's stdout.
4081 os2emx_popen2(PyObject
*self
, PyObject
*args
)
4089 if (!PyArg_ParseTuple(args
, "s|si:popen2", &cmdstring
, &mode
, &bufsize
))
4094 else if (*mode
!= 'b') {
4095 PyErr_SetString(PyExc_ValueError
, "mode must be 't' or 'b'");
4100 f
= _PyPopen(cmdstring
, tm
, POPEN_2
, bufsize
);
4106 * Variation on os2emx.popen2
4108 * The result of this function is 3 pipes - the process's stdin,
4113 os2emx_popen3(PyObject
*self
, PyObject
*args
)
4121 if (!PyArg_ParseTuple(args
, "s|si:popen3", &cmdstring
, &mode
, &bufsize
))
4126 else if (*mode
!= 'b') {
4127 PyErr_SetString(PyExc_ValueError
, "mode must be 't' or 'b'");
4132 f
= _PyPopen(cmdstring
, tm
, POPEN_3
, bufsize
);
4138 * Variation on os2emx.popen2
4140 * The result of this function is 2 pipes - the processes stdin,
4141 * and stdout+stderr combined as a single pipe.
4145 os2emx_popen4(PyObject
*self
, PyObject
*args
)
4153 if (!PyArg_ParseTuple(args
, "s|si:popen4", &cmdstring
, &mode
, &bufsize
))
4158 else if (*mode
!= 'b') {
4159 PyErr_SetString(PyExc_ValueError
, "mode must be 't' or 'b'");
4164 f
= _PyPopen(cmdstring
, tm
, POPEN_4
, bufsize
);
4169 /* a couple of structures for convenient handling of multiple
4170 * file handles and pipes
4184 /* The following code is derived from the win32 code */
4187 _PyPopen(char *cmdstring
, int mode
, int n
, int bufsize
)
4189 struct file_ref stdio
[3];
4190 struct pipe_ref p_fd
[3];
4192 int file_count
, i
, pipe_err
, pipe_pid
;
4193 char *shell
, *sh_name
, *opt
, *rd_mode
, *wr_mode
;
4194 PyObject
*f
, *p_f
[3];
4196 /* file modes for subsequent fdopen's on pipe handles */
4208 /* prepare shell references */
4209 if ((shell
= getenv("EMXSHELL")) == NULL
)
4210 if ((shell
= getenv("COMSPEC")) == NULL
)
4213 return posix_error();
4216 sh_name
= _getname(shell
);
4217 if (stricmp(sh_name
, "cmd.exe") == 0 || stricmp(sh_name
, "4os2.exe") == 0)
4222 /* save current stdio fds + their flags, and set not inheritable */
4224 while (pipe_err
>= 0 && i
< 3)
4226 pipe_err
= stdio
[i
].handle
= dup(i
);
4227 stdio
[i
].flags
= fcntl(i
, F_GETFD
, 0);
4228 fcntl(stdio
[i
].handle
, F_SETFD
, stdio
[i
].flags
| FD_CLOEXEC
);
4233 /* didn't get them all saved - clean up and bail out */
4234 int saved_err
= errno
;
4237 close(stdio
[i
].handle
);
4240 return posix_error();
4243 /* create pipe ends */
4248 while ((pipe_err
== 0) && (i
< file_count
))
4249 pipe_err
= pipe((int *)&p_fd
[i
++]);
4252 /* didn't get them all made - clean up and bail out */
4259 return posix_error();
4262 /* change the actual standard IO streams over temporarily,
4263 * making the retained pipe ends non-inheritable
4268 if (dup2(p_fd
[0].rd
, 0) == 0)
4271 i
= fcntl(p_fd
[0].wr
, F_GETFD
, 0);
4272 fcntl(p_fd
[0].wr
, F_SETFD
, i
| FD_CLOEXEC
);
4273 if ((p_s
[0] = fdopen(p_fd
[0].wr
, wr_mode
)) == NULL
)
4287 if (dup2(p_fd
[1].wr
, 1) == 1)
4290 i
= fcntl(p_fd
[1].rd
, F_GETFD
, 0);
4291 fcntl(p_fd
[1].rd
, F_SETFD
, i
| FD_CLOEXEC
);
4292 if ((p_s
[1] = fdopen(p_fd
[1].rd
, rd_mode
)) == NULL
)
4304 /* - stderr, as required */
4310 if (dup2(p_fd
[2].wr
, 2) == 2)
4313 i
= fcntl(p_fd
[2].rd
, F_GETFD
, 0);
4314 fcntl(p_fd
[2].rd
, F_SETFD
, i
| FD_CLOEXEC
);
4315 if ((p_s
[2] = fdopen(p_fd
[2].rd
, rd_mode
)) == NULL
)
4330 if (dup2(1, 2) != 2)
4338 /* spawn the child process */
4341 pipe_pid
= spawnlp(P_NOWAIT
, shell
, shell
, opt
, cmdstring
, (char *)0);
4348 /* save the PID into the FILE structure
4349 * NOTE: this implementation doesn't actually
4350 * take advantage of this, but do it for
4351 * completeness - AIM Apr01
4353 for (i
= 0; i
< file_count
; i
++)
4354 p_s
[i
]->_pid
= pipe_pid
;
4358 /* reset standard IO to normal */
4359 for (i
= 0; i
< 3; i
++)
4361 dup2(stdio
[i
].handle
, i
);
4362 fcntl(i
, F_SETFD
, stdio
[i
].flags
);
4363 close(stdio
[i
].handle
);
4366 /* if any remnant problems, clean up and bail out */
4369 for (i
= 0; i
< 3; i
++)
4375 return posix_error_with_filename(cmdstring
);
4378 /* build tuple of file objects to return */
4379 if ((p_f
[0] = PyFile_FromFile(p_s
[0], cmdstring
, wr_mode
, _PyPclose
)) != NULL
)
4380 PyFile_SetBufSize(p_f
[0], bufsize
);
4381 if ((p_f
[1] = PyFile_FromFile(p_s
[1], cmdstring
, rd_mode
, _PyPclose
)) != NULL
)
4382 PyFile_SetBufSize(p_f
[1], bufsize
);
4385 if ((p_f
[2] = PyFile_FromFile(p_s
[2], cmdstring
, rd_mode
, _PyPclose
)) != NULL
)
4386 PyFile_SetBufSize(p_f
[0], bufsize
);
4387 f
= PyTuple_Pack(3, p_f
[0], p_f
[1], p_f
[2]);
4390 f
= PyTuple_Pack(2, p_f
[0], p_f
[1]);
4393 * Insert the files we've created into the process dictionary
4394 * all referencing the list with the process handle and the
4395 * initial number of files (see description below in _PyPclose).
4396 * Since if _PyPclose later tried to wait on a process when all
4397 * handles weren't closed, it could create a deadlock with the
4398 * child, we spend some energy here to try to ensure that we
4399 * either insert all file handles into the dictionary or none
4400 * at all. It's a little clumsy with the various popen modes
4401 * and variable number of files involved.
4405 _PyPopenProcs
= PyDict_New();
4410 PyObject
*procObj
, *pidObj
, *intObj
, *fileObj
[3];
4413 fileObj
[0] = fileObj
[1] = fileObj
[2] = NULL
;
4414 ins_rc
[0] = ins_rc
[1] = ins_rc
[2] = 0;
4416 procObj
= PyList_New(2);
4417 pidObj
= PyInt_FromLong((long) pipe_pid
);
4418 intObj
= PyInt_FromLong((long) file_count
);
4420 if (procObj
&& pidObj
&& intObj
)
4422 PyList_SetItem(procObj
, 0, pidObj
);
4423 PyList_SetItem(procObj
, 1, intObj
);
4425 fileObj
[0] = PyLong_FromVoidPtr(p_s
[0]);
4428 ins_rc
[0] = PyDict_SetItem(_PyPopenProcs
,
4432 fileObj
[1] = PyLong_FromVoidPtr(p_s
[1]);
4435 ins_rc
[1] = PyDict_SetItem(_PyPopenProcs
,
4439 if (file_count
>= 3)
4441 fileObj
[2] = PyLong_FromVoidPtr(p_s
[2]);
4444 ins_rc
[2] = PyDict_SetItem(_PyPopenProcs
,
4450 if (ins_rc
[0] < 0 || !fileObj
[0] ||
4451 ins_rc
[1] < 0 || (file_count
> 1 && !fileObj
[1]) ||
4452 ins_rc
[2] < 0 || (file_count
> 2 && !fileObj
[2]))
4454 /* Something failed - remove any dictionary
4455 * entries that did make it.
4457 if (!ins_rc
[0] && fileObj
[0])
4459 PyDict_DelItem(_PyPopenProcs
,
4462 if (!ins_rc
[1] && fileObj
[1])
4464 PyDict_DelItem(_PyPopenProcs
,
4467 if (!ins_rc
[2] && fileObj
[2])
4469 PyDict_DelItem(_PyPopenProcs
,
4476 * Clean up our localized references for the dictionary keys
4477 * and value since PyDict_SetItem will Py_INCREF any copies
4478 * that got placed in the dictionary.
4480 Py_XDECREF(procObj
);
4481 Py_XDECREF(fileObj
[0]);
4482 Py_XDECREF(fileObj
[1]);
4483 Py_XDECREF(fileObj
[2]);
4486 /* Child is launched. */
4491 * Wrapper for fclose() to use for popen* files, so we can retrieve the
4492 * exit code for the child process and return as a result of the close.
4494 * This function uses the _PyPopenProcs dictionary in order to map the
4495 * input file pointer to information about the process that was
4496 * originally created by the popen* call that created the file pointer.
4497 * The dictionary uses the file pointer as a key (with one entry
4498 * inserted for each file returned by the original popen* call) and a
4499 * single list object as the value for all files from a single call.
4500 * The list object contains the Win32 process handle at [0], and a file
4501 * count at [1], which is initialized to the total number of file
4502 * handles using that list.
4504 * This function closes whichever handle it is passed, and decrements
4505 * the file count in the dictionary for the process handle pointed to
4506 * by this file. On the last close (when the file count reaches zero),
4507 * this function will wait for the child process and then return its
4508 * exit code as the result of the close() operation. This permits the
4509 * files to be closed in any order - it is always the close() of the
4510 * final handle that will return the exit code.
4512 * NOTE: This function is currently called with the GIL released.
4513 * hence we use the GILState API to manage our state.
4516 static int _PyPclose(FILE *file
)
4521 PyObject
*procObj
, *pidObj
, *intObj
, *fileObj
;
4524 PyGILState_STATE state
;
4527 /* Close the file handle first, to ensure it can't block the
4528 * child from exiting if it's the last handle.
4530 result
= fclose(file
);
4533 state
= PyGILState_Ensure();
4537 if ((fileObj
= PyLong_FromVoidPtr(file
)) != NULL
&&
4538 (procObj
= PyDict_GetItem(_PyPopenProcs
,
4539 fileObj
)) != NULL
&&
4540 (pidObj
= PyList_GetItem(procObj
,0)) != NULL
&&
4541 (intObj
= PyList_GetItem(procObj
,1)) != NULL
)
4543 pipe_pid
= (int) PyInt_AsLong(pidObj
);
4544 file_count
= (int) PyInt_AsLong(intObj
);
4548 /* Still other files referencing process */
4550 PyList_SetItem(procObj
,1,
4551 PyInt_FromLong((long) file_count
));
4555 /* Last file for this process */
4556 if (result
!= EOF
&&
4557 waitpid(pipe_pid
, &exit_code
, 0) == pipe_pid
)
4559 /* extract exit status */
4560 if (WIFEXITED(exit_code
))
4562 result
= WEXITSTATUS(exit_code
);
4572 /* Indicate failure - this will cause the file object
4573 * to raise an I/O error and translate the last
4574 * error code from errno. We do have a problem with
4575 * last errors that overlap the normal errno table,
4576 * but that's a consistent problem with the file object.
4582 /* Remove this file pointer from dictionary */
4583 PyDict_DelItem(_PyPopenProcs
, fileObj
);
4585 if (PyDict_Size(_PyPopenProcs
) == 0)
4587 Py_DECREF(_PyPopenProcs
);
4588 _PyPopenProcs
= NULL
;
4591 } /* if object retrieval ok */
4593 Py_XDECREF(fileObj
);
4594 } /* if _PyPopenProcs */
4597 PyGILState_Release(state
);
4602 #endif /* PYCC_??? */
4604 #elif defined(MS_WINDOWS)
4607 * Portable 'popen' replacement for Win32.
4609 * Written by Bill Tutt <billtut@microsoft.com>. Minor tweaks
4610 * and 2.0 integration by Fredrik Lundh <fredrik@pythonware.com>
4611 * Return code handling by David Bolen <db3l@fitlinxx.com>.
4618 /* These tell _PyPopen() wether to return 1, 2, or 3 file objects. */
4624 static PyObject
*_PyPopen(char *, int, int);
4625 static int _PyPclose(FILE *file
);
4628 * Internal dictionary mapping popen* file pointers to process handles,
4629 * for use when retrieving the process exit code. See _PyPclose() below
4630 * for more information on this dictionary's use.
4632 static PyObject
*_PyPopenProcs
= NULL
;
4635 /* popen that works from a GUI.
4637 * The result of this function is a pipe (file) connected to the
4638 * processes stdin or stdout, depending on the requested mode.
4642 posix_popen(PyObject
*self
, PyObject
*args
)
4650 if (!PyArg_ParseTuple(args
, "s|si:popen", &cmdstring
, &mode
, &bufsize
))
4655 else if (*mode
!= 'w') {
4656 PyErr_SetString(PyExc_ValueError
, "popen() arg 2 must be 'r' or 'w'");
4661 if (bufsize
!= -1) {
4662 PyErr_SetString(PyExc_ValueError
, "popen() arg 3 must be -1");
4666 if (*(mode
+1) == 't')
4667 f
= _PyPopen(cmdstring
, tm
| _O_TEXT
, POPEN_1
);
4668 else if (*(mode
+1) == 'b')
4669 f
= _PyPopen(cmdstring
, tm
| _O_BINARY
, POPEN_1
);
4671 f
= _PyPopen(cmdstring
, tm
| _O_TEXT
, POPEN_1
);
4676 /* Variation on win32pipe.popen
4678 * The result of this function is a pipe (file) connected to the
4679 * process's stdin, and a pipe connected to the process's stdout.
4683 win32_popen2(PyObject
*self
, PyObject
*args
)
4691 if (!PyArg_ParseTuple(args
, "s|si:popen2", &cmdstring
, &mode
, &bufsize
))
4696 else if (*mode
!= 'b') {
4697 PyErr_SetString(PyExc_ValueError
, "popen2() arg 2 must be 't' or 'b'");
4702 if (bufsize
!= -1) {
4703 PyErr_SetString(PyExc_ValueError
, "popen2() arg 3 must be -1");
4707 f
= _PyPopen(cmdstring
, tm
, POPEN_2
);
4713 * Variation on <om win32pipe.popen>
4715 * The result of this function is 3 pipes - the process's stdin,
4720 win32_popen3(PyObject
*self
, PyObject
*args
)
4728 if (!PyArg_ParseTuple(args
, "s|si:popen3", &cmdstring
, &mode
, &bufsize
))
4733 else if (*mode
!= 'b') {
4734 PyErr_SetString(PyExc_ValueError
, "popen3() arg 2 must be 't' or 'b'");
4739 if (bufsize
!= -1) {
4740 PyErr_SetString(PyExc_ValueError
, "popen3() arg 3 must be -1");
4744 f
= _PyPopen(cmdstring
, tm
, POPEN_3
);
4750 * Variation on win32pipe.popen
4752 * The result of this function is 2 pipes - the processes stdin,
4753 * and stdout+stderr combined as a single pipe.
4757 win32_popen4(PyObject
*self
, PyObject
*args
)
4765 if (!PyArg_ParseTuple(args
, "s|si:popen4", &cmdstring
, &mode
, &bufsize
))
4770 else if (*mode
!= 'b') {
4771 PyErr_SetString(PyExc_ValueError
, "popen4() arg 2 must be 't' or 'b'");
4776 if (bufsize
!= -1) {
4777 PyErr_SetString(PyExc_ValueError
, "popen4() arg 3 must be -1");
4781 f
= _PyPopen(cmdstring
, tm
, POPEN_4
);
4787 _PyPopenCreateProcess(char *cmdstring
,
4793 PROCESS_INFORMATION piProcInfo
;
4794 STARTUPINFO siStartInfo
;
4795 DWORD dwProcessFlags
= 0; /* no NEW_CONSOLE by default for Ctrl+C handling */
4796 char *s1
,*s2
, *s3
= " /c ";
4797 const char *szConsoleSpawn
= "w9xpopen.exe";
4801 if (i
= GetEnvironmentVariable("COMSPEC",NULL
,0)) {
4804 s1
= (char *)alloca(i
);
4805 if (!(x
= GetEnvironmentVariable("COMSPEC", s1
, i
)))
4806 /* x < i, so x fits into an integer */
4809 /* Explicitly check if we are using COMMAND.COM. If we are
4810 * then use the w9xpopen hack.
4813 while (comshell
>= s1
&& *comshell
!= '\\')
4817 if (GetVersion() < 0x80000000 &&
4818 _stricmp(comshell
, "command.com") != 0) {
4819 /* NT/2000 and not using command.com. */
4820 x
= i
+ strlen(s3
) + strlen(cmdstring
) + 1;
4821 s2
= (char *)alloca(x
);
4823 PyOS_snprintf(s2
, x
, "%s%s%s", s1
, s3
, cmdstring
);
4827 * Oh gag, we're on Win9x or using COMMAND.COM. Use
4828 * the workaround listed in KB: Q150956
4830 char modulepath
[_MAX_PATH
];
4831 struct stat statinfo
;
4832 GetModuleFileName(NULL
, modulepath
, sizeof(modulepath
));
4833 for (x
= i
= 0; modulepath
[i
]; i
++)
4834 if (modulepath
[i
] == SEP
)
4836 modulepath
[x
] = '\0';
4837 /* Create the full-name to w9xpopen, so we can test it exists */
4840 (sizeof(modulepath
)/sizeof(modulepath
[0]))
4841 -strlen(modulepath
));
4842 if (stat(modulepath
, &statinfo
) != 0) {
4843 size_t mplen
= sizeof(modulepath
)/sizeof(modulepath
[0]);
4844 /* Eeek - file-not-found - possibly an embedding
4845 situation - see if we can locate it in sys.prefix
4850 modulepath
[mplen
-1] = '\0';
4851 if (modulepath
[strlen(modulepath
)-1] != '\\')
4852 strcat(modulepath
, "\\");
4855 mplen
-strlen(modulepath
));
4856 /* No where else to look - raise an easily identifiable
4857 error, rather than leaving Windows to report
4858 "file not found" - as the user is probably blissfully
4859 unaware this shim EXE is used, and it will confuse them.
4860 (well, it confused me for a while ;-)
4862 if (stat(modulepath
, &statinfo
) != 0) {
4863 PyErr_Format(PyExc_RuntimeError
,
4864 "Can not locate '%s' which is needed "
4865 "for popen to work with your shell "
4871 x
= i
+ strlen(s3
) + strlen(cmdstring
) + 1 +
4872 strlen(modulepath
) +
4873 strlen(szConsoleSpawn
) + 1;
4875 s2
= (char *)alloca(x
);
4877 /* To maintain correct argument passing semantics,
4878 we pass the command-line as it stands, and allow
4879 quoting to be applied. w9xpopen.exe will then
4880 use its argv vector, and re-quote the necessary
4881 args for the ultimate child process.
4890 /* Not passing CREATE_NEW_CONSOLE has been known to
4891 cause random failures on win9x. Specifically a
4893 "Your program accessed mem currently in use at xxx"
4894 and a hopeful warning about the stability of your
4896 Cost is Ctrl+C wont kill children, but anyone
4897 who cares can have a go!
4899 dwProcessFlags
|= CREATE_NEW_CONSOLE
;
4903 /* Could be an else here to try cmd.exe / command.com in the path
4904 Now we'll just error out.. */
4906 PyErr_SetString(PyExc_RuntimeError
,
4907 "Cannot locate a COMSPEC environment variable to "
4908 "use as the shell");
4912 ZeroMemory(&siStartInfo
, sizeof(STARTUPINFO
));
4913 siStartInfo
.cb
= sizeof(STARTUPINFO
);
4914 siStartInfo
.dwFlags
= STARTF_USESTDHANDLES
| STARTF_USESHOWWINDOW
;
4915 siStartInfo
.hStdInput
= hStdin
;
4916 siStartInfo
.hStdOutput
= hStdout
;
4917 siStartInfo
.hStdError
= hStderr
;
4918 siStartInfo
.wShowWindow
= SW_HIDE
;
4920 if (CreateProcess(NULL
,
4930 /* Close the handles now so anyone waiting is woken. */
4931 CloseHandle(piProcInfo
.hThread
);
4933 /* Return process handle */
4934 *hProcess
= piProcInfo
.hProcess
;
4937 win32_error("CreateProcess", s2
);
4941 /* The following code is based off of KB: Q190351 */
4944 _PyPopen(char *cmdstring
, int mode
, int n
)
4946 HANDLE hChildStdinRd
, hChildStdinWr
, hChildStdoutRd
, hChildStdoutWr
,
4947 hChildStderrRd
, hChildStderrWr
, hChildStdinWrDup
, hChildStdoutRdDup
,
4948 hChildStderrRdDup
, hProcess
; /* hChildStdoutWrDup; */
4950 SECURITY_ATTRIBUTES saAttr
;
4957 saAttr
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
4958 saAttr
.bInheritHandle
= TRUE
;
4959 saAttr
.lpSecurityDescriptor
= NULL
;
4961 if (!CreatePipe(&hChildStdinRd
, &hChildStdinWr
, &saAttr
, 0))
4962 return win32_error("CreatePipe", NULL
);
4964 /* Create new output read handle and the input write handle. Set
4965 * the inheritance properties to FALSE. Otherwise, the child inherits
4966 * these handles; resulting in non-closeable handles to the pipes
4968 fSuccess
= DuplicateHandle(GetCurrentProcess(), hChildStdinWr
,
4969 GetCurrentProcess(), &hChildStdinWrDup
, 0,
4971 DUPLICATE_SAME_ACCESS
);
4973 return win32_error("DuplicateHandle", NULL
);
4975 /* Close the inheritable version of ChildStdin
4976 that we're using. */
4977 CloseHandle(hChildStdinWr
);
4979 if (!CreatePipe(&hChildStdoutRd
, &hChildStdoutWr
, &saAttr
, 0))
4980 return win32_error("CreatePipe", NULL
);
4982 fSuccess
= DuplicateHandle(GetCurrentProcess(), hChildStdoutRd
,
4983 GetCurrentProcess(), &hChildStdoutRdDup
, 0,
4984 FALSE
, DUPLICATE_SAME_ACCESS
);
4986 return win32_error("DuplicateHandle", NULL
);
4988 /* Close the inheritable version of ChildStdout
4989 that we're using. */
4990 CloseHandle(hChildStdoutRd
);
4993 if (!CreatePipe(&hChildStderrRd
, &hChildStderrWr
, &saAttr
, 0))
4994 return win32_error("CreatePipe", NULL
);
4995 fSuccess
= DuplicateHandle(GetCurrentProcess(),
4997 GetCurrentProcess(),
4998 &hChildStderrRdDup
, 0,
4999 FALSE
, DUPLICATE_SAME_ACCESS
);
5001 return win32_error("DuplicateHandle", NULL
);
5002 /* Close the inheritable version of ChildStdErr that we're using. */
5003 CloseHandle(hChildStderrRd
);
5008 switch (mode
& (_O_RDONLY
| _O_TEXT
| _O_BINARY
| _O_WRONLY
)) {
5009 case _O_WRONLY
| _O_TEXT
:
5010 /* Case for writing to child Stdin in text mode. */
5011 fd1
= _open_osfhandle((Py_intptr_t
)hChildStdinWrDup
, mode
);
5012 f1
= _fdopen(fd1
, "w");
5013 f
= PyFile_FromFile(f1
, cmdstring
, "w", _PyPclose
);
5014 PyFile_SetBufSize(f
, 0);
5015 /* We don't care about these pipes anymore, so close them. */
5016 CloseHandle(hChildStdoutRdDup
);
5017 CloseHandle(hChildStderrRdDup
);
5020 case _O_RDONLY
| _O_TEXT
:
5021 /* Case for reading from child Stdout in text mode. */
5022 fd1
= _open_osfhandle((Py_intptr_t
)hChildStdoutRdDup
, mode
);
5023 f1
= _fdopen(fd1
, "r");
5024 f
= PyFile_FromFile(f1
, cmdstring
, "r", _PyPclose
);
5025 PyFile_SetBufSize(f
, 0);
5026 /* We don't care about these pipes anymore, so close them. */
5027 CloseHandle(hChildStdinWrDup
);
5028 CloseHandle(hChildStderrRdDup
);
5031 case _O_RDONLY
| _O_BINARY
:
5032 /* Case for readinig from child Stdout in binary mode. */
5033 fd1
= _open_osfhandle((Py_intptr_t
)hChildStdoutRdDup
, mode
);
5034 f1
= _fdopen(fd1
, "rb");
5035 f
= PyFile_FromFile(f1
, cmdstring
, "rb", _PyPclose
);
5036 PyFile_SetBufSize(f
, 0);
5037 /* We don't care about these pipes anymore, so close them. */
5038 CloseHandle(hChildStdinWrDup
);
5039 CloseHandle(hChildStderrRdDup
);
5042 case _O_WRONLY
| _O_BINARY
:
5043 /* Case for writing to child Stdin in binary mode. */
5044 fd1
= _open_osfhandle((Py_intptr_t
)hChildStdinWrDup
, mode
);
5045 f1
= _fdopen(fd1
, "wb");
5046 f
= PyFile_FromFile(f1
, cmdstring
, "wb", _PyPclose
);
5047 PyFile_SetBufSize(f
, 0);
5048 /* We don't care about these pipes anymore, so close them. */
5049 CloseHandle(hChildStdoutRdDup
);
5050 CloseHandle(hChildStderrRdDup
);
5062 if (mode
& _O_TEXT
) {
5070 fd1
= _open_osfhandle((Py_intptr_t
)hChildStdinWrDup
, mode
);
5071 f1
= _fdopen(fd1
, m2
);
5072 fd2
= _open_osfhandle((Py_intptr_t
)hChildStdoutRdDup
, mode
);
5073 f2
= _fdopen(fd2
, m1
);
5074 p1
= PyFile_FromFile(f1
, cmdstring
, m2
, _PyPclose
);
5075 PyFile_SetBufSize(p1
, 0);
5076 p2
= PyFile_FromFile(f2
, cmdstring
, m1
, _PyPclose
);
5077 PyFile_SetBufSize(p2
, 0);
5080 CloseHandle(hChildStderrRdDup
);
5082 f
= PyTuple_Pack(2,p1
,p2
);
5092 PyObject
*p1
, *p2
, *p3
;
5094 if (mode
& _O_TEXT
) {
5102 fd1
= _open_osfhandle((Py_intptr_t
)hChildStdinWrDup
, mode
);
5103 f1
= _fdopen(fd1
, m2
);
5104 fd2
= _open_osfhandle((Py_intptr_t
)hChildStdoutRdDup
, mode
);
5105 f2
= _fdopen(fd2
, m1
);
5106 fd3
= _open_osfhandle((Py_intptr_t
)hChildStderrRdDup
, mode
);
5107 f3
= _fdopen(fd3
, m1
);
5108 p1
= PyFile_FromFile(f1
, cmdstring
, m2
, _PyPclose
);
5109 p2
= PyFile_FromFile(f2
, cmdstring
, m1
, _PyPclose
);
5110 p3
= PyFile_FromFile(f3
, cmdstring
, m1
, _PyPclose
);
5111 PyFile_SetBufSize(p1
, 0);
5112 PyFile_SetBufSize(p2
, 0);
5113 PyFile_SetBufSize(p3
, 0);
5114 f
= PyTuple_Pack(3,p1
,p2
,p3
);
5124 if (!_PyPopenCreateProcess(cmdstring
,
5132 if (!_PyPopenCreateProcess(cmdstring
,
5141 * Insert the files we've created into the process dictionary
5142 * all referencing the list with the process handle and the
5143 * initial number of files (see description below in _PyPclose).
5144 * Since if _PyPclose later tried to wait on a process when all
5145 * handles weren't closed, it could create a deadlock with the
5146 * child, we spend some energy here to try to ensure that we
5147 * either insert all file handles into the dictionary or none
5148 * at all. It's a little clumsy with the various popen modes
5149 * and variable number of files involved.
5151 if (!_PyPopenProcs
) {
5152 _PyPopenProcs
= PyDict_New();
5155 if (_PyPopenProcs
) {
5156 PyObject
*procObj
, *hProcessObj
, *intObj
, *fileObj
[3];
5159 fileObj
[0] = fileObj
[1] = fileObj
[2] = NULL
;
5160 ins_rc
[0] = ins_rc
[1] = ins_rc
[2] = 0;
5162 procObj
= PyList_New(2);
5163 hProcessObj
= PyLong_FromVoidPtr(hProcess
);
5164 intObj
= PyInt_FromLong(file_count
);
5166 if (procObj
&& hProcessObj
&& intObj
) {
5167 PyList_SetItem(procObj
,0,hProcessObj
);
5168 PyList_SetItem(procObj
,1,intObj
);
5170 fileObj
[0] = PyLong_FromVoidPtr(f1
);
5172 ins_rc
[0] = PyDict_SetItem(_PyPopenProcs
,
5176 if (file_count
>= 2) {
5177 fileObj
[1] = PyLong_FromVoidPtr(f2
);
5179 ins_rc
[1] = PyDict_SetItem(_PyPopenProcs
,
5184 if (file_count
>= 3) {
5185 fileObj
[2] = PyLong_FromVoidPtr(f3
);
5187 ins_rc
[2] = PyDict_SetItem(_PyPopenProcs
,
5193 if (ins_rc
[0] < 0 || !fileObj
[0] ||
5194 ins_rc
[1] < 0 || (file_count
> 1 && !fileObj
[1]) ||
5195 ins_rc
[2] < 0 || (file_count
> 2 && !fileObj
[2])) {
5196 /* Something failed - remove any dictionary
5197 * entries that did make it.
5199 if (!ins_rc
[0] && fileObj
[0]) {
5200 PyDict_DelItem(_PyPopenProcs
,
5203 if (!ins_rc
[1] && fileObj
[1]) {
5204 PyDict_DelItem(_PyPopenProcs
,
5207 if (!ins_rc
[2] && fileObj
[2]) {
5208 PyDict_DelItem(_PyPopenProcs
,
5215 * Clean up our localized references for the dictionary keys
5216 * and value since PyDict_SetItem will Py_INCREF any copies
5217 * that got placed in the dictionary.
5219 Py_XDECREF(procObj
);
5220 Py_XDECREF(fileObj
[0]);
5221 Py_XDECREF(fileObj
[1]);
5222 Py_XDECREF(fileObj
[2]);
5225 /* Child is launched. Close the parents copy of those pipe
5226 * handles that only the child should have open. You need to
5227 * make sure that no handles to the write end of the output pipe
5228 * are maintained in this process or else the pipe will not close
5229 * when the child process exits and the ReadFile will hang. */
5231 if (!CloseHandle(hChildStdinRd
))
5232 return win32_error("CloseHandle", NULL
);
5234 if (!CloseHandle(hChildStdoutWr
))
5235 return win32_error("CloseHandle", NULL
);
5237 if ((n
!= 4) && (!CloseHandle(hChildStderrWr
)))
5238 return win32_error("CloseHandle", NULL
);
5244 * Wrapper for fclose() to use for popen* files, so we can retrieve the
5245 * exit code for the child process and return as a result of the close.
5247 * This function uses the _PyPopenProcs dictionary in order to map the
5248 * input file pointer to information about the process that was
5249 * originally created by the popen* call that created the file pointer.
5250 * The dictionary uses the file pointer as a key (with one entry
5251 * inserted for each file returned by the original popen* call) and a
5252 * single list object as the value for all files from a single call.
5253 * The list object contains the Win32 process handle at [0], and a file
5254 * count at [1], which is initialized to the total number of file
5255 * handles using that list.
5257 * This function closes whichever handle it is passed, and decrements
5258 * the file count in the dictionary for the process handle pointed to
5259 * by this file. On the last close (when the file count reaches zero),
5260 * this function will wait for the child process and then return its
5261 * exit code as the result of the close() operation. This permits the
5262 * files to be closed in any order - it is always the close() of the
5263 * final handle that will return the exit code.
5265 * NOTE: This function is currently called with the GIL released.
5266 * hence we use the GILState API to manage our state.
5269 static int _PyPclose(FILE *file
)
5274 PyObject
*procObj
, *hProcessObj
, *intObj
, *fileObj
;
5277 PyGILState_STATE state
;
5280 /* Close the file handle first, to ensure it can't block the
5281 * child from exiting if it's the last handle.
5283 result
= fclose(file
);
5285 state
= PyGILState_Ensure();
5287 if (_PyPopenProcs
) {
5288 if ((fileObj
= PyLong_FromVoidPtr(file
)) != NULL
&&
5289 (procObj
= PyDict_GetItem(_PyPopenProcs
,
5290 fileObj
)) != NULL
&&
5291 (hProcessObj
= PyList_GetItem(procObj
,0)) != NULL
&&
5292 (intObj
= PyList_GetItem(procObj
,1)) != NULL
) {
5294 hProcess
= PyLong_AsVoidPtr(hProcessObj
);
5295 file_count
= PyInt_AsLong(intObj
);
5297 if (file_count
> 1) {
5298 /* Still other files referencing process */
5300 PyList_SetItem(procObj
,1,
5301 PyInt_FromLong(file_count
));
5303 /* Last file for this process */
5304 if (result
!= EOF
&&
5305 WaitForSingleObject(hProcess
, INFINITE
) != WAIT_FAILED
&&
5306 GetExitCodeProcess(hProcess
, &exit_code
)) {
5307 /* Possible truncation here in 16-bit environments, but
5308 * real exit codes are just the lower byte in any event.
5312 /* Indicate failure - this will cause the file object
5313 * to raise an I/O error and translate the last Win32
5314 * error code from errno. We do have a problem with
5315 * last errors that overlap the normal errno table,
5316 * but that's a consistent problem with the file object.
5318 if (result
!= EOF
) {
5319 /* If the error wasn't from the fclose(), then
5320 * set errno for the file object error handling.
5322 errno
= GetLastError();
5327 /* Free up the native handle at this point */
5328 CloseHandle(hProcess
);
5331 /* Remove this file pointer from dictionary */
5332 PyDict_DelItem(_PyPopenProcs
, fileObj
);
5334 if (PyDict_Size(_PyPopenProcs
) == 0) {
5335 Py_DECREF(_PyPopenProcs
);
5336 _PyPopenProcs
= NULL
;
5339 } /* if object retrieval ok */
5341 Py_XDECREF(fileObj
);
5342 } /* if _PyPopenProcs */
5345 PyGILState_Release(state
);
5350 #else /* which OS? */
5352 posix_popen(PyObject
*self
, PyObject
*args
)
5359 if (!PyArg_ParseTuple(args
, "s|si:popen", &name
, &mode
, &bufsize
))
5361 /* Strip mode of binary or text modifiers */
5362 if (strcmp(mode
, "rb") == 0 || strcmp(mode
, "rt") == 0)
5364 else if (strcmp(mode
, "wb") == 0 || strcmp(mode
, "wt") == 0)
5366 Py_BEGIN_ALLOW_THREADS
5367 fp
= popen(name
, mode
);
5368 Py_END_ALLOW_THREADS
5370 return posix_error();
5371 f
= PyFile_FromFile(fp
, name
, mode
, pclose
);
5373 PyFile_SetBufSize(f
, bufsize
);
5377 #endif /* PYOS_??? */
5378 #endif /* HAVE_POPEN */
5382 PyDoc_STRVAR(posix_setuid__doc__
,
5384 Set the current process's user id.");
5387 posix_setuid(PyObject
*self
, PyObject
*args
)
5390 if (!PyArg_ParseTuple(args
, "i:setuid", &uid
))
5392 if (setuid(uid
) < 0)
5393 return posix_error();
5397 #endif /* HAVE_SETUID */
5401 PyDoc_STRVAR(posix_seteuid__doc__
,
5403 Set the current process's effective user id.");
5406 posix_seteuid (PyObject
*self
, PyObject
*args
)
5409 if (!PyArg_ParseTuple(args
, "i", &euid
)) {
5411 } else if (seteuid(euid
) < 0) {
5412 return posix_error();
5418 #endif /* HAVE_SETEUID */
5421 PyDoc_STRVAR(posix_setegid__doc__
,
5423 Set the current process's effective group id.");
5426 posix_setegid (PyObject
*self
, PyObject
*args
)
5429 if (!PyArg_ParseTuple(args
, "i", &egid
)) {
5431 } else if (setegid(egid
) < 0) {
5432 return posix_error();
5438 #endif /* HAVE_SETEGID */
5440 #ifdef HAVE_SETREUID
5441 PyDoc_STRVAR(posix_setreuid__doc__
,
5442 "setreuid(ruid, euid)\n\n\
5443 Set the current process's real and effective user ids.");
5446 posix_setreuid (PyObject
*self
, PyObject
*args
)
5449 if (!PyArg_ParseTuple(args
, "ii", &ruid
, &euid
)) {
5451 } else if (setreuid(ruid
, euid
) < 0) {
5452 return posix_error();
5458 #endif /* HAVE_SETREUID */
5460 #ifdef HAVE_SETREGID
5461 PyDoc_STRVAR(posix_setregid__doc__
,
5462 "setregid(rgid, egid)\n\n\
5463 Set the current process's real and effective group ids.");
5466 posix_setregid (PyObject
*self
, PyObject
*args
)
5469 if (!PyArg_ParseTuple(args
, "ii", &rgid
, &egid
)) {
5471 } else if (setregid(rgid
, egid
) < 0) {
5472 return posix_error();
5478 #endif /* HAVE_SETREGID */
5481 PyDoc_STRVAR(posix_setgid__doc__
,
5483 Set the current process's group id.");
5486 posix_setgid(PyObject
*self
, PyObject
*args
)
5489 if (!PyArg_ParseTuple(args
, "i:setgid", &gid
))
5491 if (setgid(gid
) < 0)
5492 return posix_error();
5496 #endif /* HAVE_SETGID */
5498 #ifdef HAVE_SETGROUPS
5499 PyDoc_STRVAR(posix_setgroups__doc__
,
5500 "setgroups(list)\n\n\
5501 Set the groups of the current process to list.");
5504 posix_setgroups(PyObject
*self
, PyObject
*groups
)
5507 gid_t grouplist
[MAX_GROUPS
];
5509 if (!PySequence_Check(groups
)) {
5510 PyErr_SetString(PyExc_TypeError
, "setgroups argument must be a sequence");
5513 len
= PySequence_Size(groups
);
5514 if (len
> MAX_GROUPS
) {
5515 PyErr_SetString(PyExc_ValueError
, "too many groups");
5518 for(i
= 0; i
< len
; i
++) {
5520 elem
= PySequence_GetItem(groups
, i
);
5523 if (!PyInt_Check(elem
)) {
5524 if (!PyLong_Check(elem
)) {
5525 PyErr_SetString(PyExc_TypeError
,
5526 "groups must be integers");
5530 unsigned long x
= PyLong_AsUnsignedLong(elem
);
5531 if (PyErr_Occurred()) {
5532 PyErr_SetString(PyExc_TypeError
,
5533 "group id too big");
5538 /* read back the value to see if it fitted in gid_t */
5539 if (grouplist
[i
] != x
) {
5540 PyErr_SetString(PyExc_TypeError
,
5541 "group id too big");
5547 long x
= PyInt_AsLong(elem
);
5549 if (grouplist
[i
] != x
) {
5550 PyErr_SetString(PyExc_TypeError
,
5551 "group id too big");
5559 if (setgroups(len
, grouplist
) < 0)
5560 return posix_error();
5564 #endif /* HAVE_SETGROUPS */
5566 #if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
5568 wait_helper(int pid
, int status
, struct rusage
*ru
)
5571 static PyObject
*struct_rusage
;
5574 return posix_error();
5576 if (struct_rusage
== NULL
) {
5577 PyObject
*m
= PyImport_ImportModule("resource");
5580 struct_rusage
= PyObject_GetAttrString(m
, "struct_rusage");
5582 if (struct_rusage
== NULL
)
5586 /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
5587 result
= PyStructSequence_New((PyTypeObject
*) struct_rusage
);
5592 #define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
5595 PyStructSequence_SET_ITEM(result
, 0,
5596 PyFloat_FromDouble(doubletime(ru
->ru_utime
)));
5597 PyStructSequence_SET_ITEM(result
, 1,
5598 PyFloat_FromDouble(doubletime(ru
->ru_stime
)));
5599 #define SET_INT(result, index, value)\
5600 PyStructSequence_SET_ITEM(result, index, PyInt_FromLong(value))
5601 SET_INT(result
, 2, ru
->ru_maxrss
);
5602 SET_INT(result
, 3, ru
->ru_ixrss
);
5603 SET_INT(result
, 4, ru
->ru_idrss
);
5604 SET_INT(result
, 5, ru
->ru_isrss
);
5605 SET_INT(result
, 6, ru
->ru_minflt
);
5606 SET_INT(result
, 7, ru
->ru_majflt
);
5607 SET_INT(result
, 8, ru
->ru_nswap
);
5608 SET_INT(result
, 9, ru
->ru_inblock
);
5609 SET_INT(result
, 10, ru
->ru_oublock
);
5610 SET_INT(result
, 11, ru
->ru_msgsnd
);
5611 SET_INT(result
, 12, ru
->ru_msgrcv
);
5612 SET_INT(result
, 13, ru
->ru_nsignals
);
5613 SET_INT(result
, 14, ru
->ru_nvcsw
);
5614 SET_INT(result
, 15, ru
->ru_nivcsw
);
5617 if (PyErr_Occurred()) {
5622 return Py_BuildValue("iiN", pid
, status
, result
);
5624 #endif /* HAVE_WAIT3 || HAVE_WAIT4 */
5627 PyDoc_STRVAR(posix_wait3__doc__
,
5628 "wait3(options) -> (pid, status, rusage)\n\n\
5629 Wait for completion of a child process.");
5632 posix_wait3(PyObject
*self
, PyObject
*args
)
5637 WAIT_STATUS_INT(status
) = 0;
5639 if (!PyArg_ParseTuple(args
, "i:wait3", &options
))
5642 Py_BEGIN_ALLOW_THREADS
5643 pid
= wait3(&status
, options
, &ru
);
5644 Py_END_ALLOW_THREADS
5646 return wait_helper(pid
, WAIT_STATUS_INT(status
), &ru
);
5648 #endif /* HAVE_WAIT3 */
5651 PyDoc_STRVAR(posix_wait4__doc__
,
5652 "wait4(pid, options) -> (pid, status, rusage)\n\n\
5653 Wait for completion of a given child process.");
5656 posix_wait4(PyObject
*self
, PyObject
*args
)
5661 WAIT_STATUS_INT(status
) = 0;
5663 if (!PyArg_ParseTuple(args
, "ii:wait4", &pid
, &options
))
5666 Py_BEGIN_ALLOW_THREADS
5667 pid
= wait4(pid
, &status
, options
, &ru
);
5668 Py_END_ALLOW_THREADS
5670 return wait_helper(pid
, WAIT_STATUS_INT(status
), &ru
);
5672 #endif /* HAVE_WAIT4 */
5675 PyDoc_STRVAR(posix_waitpid__doc__
,
5676 "waitpid(pid, options) -> (pid, status)\n\n\
5677 Wait for completion of a given child process.");
5680 posix_waitpid(PyObject
*self
, PyObject
*args
)
5684 WAIT_STATUS_INT(status
) = 0;
5686 if (!PyArg_ParseTuple(args
, "ii:waitpid", &pid
, &options
))
5688 Py_BEGIN_ALLOW_THREADS
5689 pid
= waitpid(pid
, &status
, options
);
5690 Py_END_ALLOW_THREADS
5692 return posix_error();
5694 return Py_BuildValue("ii", pid
, WAIT_STATUS_INT(status
));
5697 #elif defined(HAVE_CWAIT)
5699 /* MS C has a variant of waitpid() that's usable for most purposes. */
5700 PyDoc_STRVAR(posix_waitpid__doc__
,
5701 "waitpid(pid, options) -> (pid, status << 8)\n\n"
5702 "Wait for completion of a given process. options is ignored on Windows.");
5705 posix_waitpid(PyObject
*self
, PyObject
*args
)
5708 int status
, options
;
5710 if (!PyArg_ParseTuple(args
, "ii:waitpid", &pid
, &options
))
5712 Py_BEGIN_ALLOW_THREADS
5713 pid
= _cwait(&status
, pid
, options
);
5714 Py_END_ALLOW_THREADS
5716 return posix_error();
5718 /* shift the status left a byte so this is more like the POSIX waitpid */
5719 return Py_BuildValue("ii", pid
, status
<< 8);
5721 #endif /* HAVE_WAITPID || HAVE_CWAIT */
5724 PyDoc_STRVAR(posix_wait__doc__
,
5725 "wait() -> (pid, status)\n\n\
5726 Wait for completion of a child process.");
5729 posix_wait(PyObject
*self
, PyObject
*noargs
)
5733 WAIT_STATUS_INT(status
) = 0;
5735 Py_BEGIN_ALLOW_THREADS
5736 pid
= wait(&status
);
5737 Py_END_ALLOW_THREADS
5739 return posix_error();
5741 return Py_BuildValue("ii", pid
, WAIT_STATUS_INT(status
));
5746 PyDoc_STRVAR(posix_lstat__doc__
,
5747 "lstat(path) -> stat result\n\n\
5748 Like stat(path), but do not follow symbolic links.");
5751 posix_lstat(PyObject
*self
, PyObject
*args
)
5754 return posix_do_stat(self
, args
, "et:lstat", lstat
, NULL
, NULL
);
5755 #else /* !HAVE_LSTAT */
5757 return posix_do_stat(self
, args
, "et:lstat", STAT
, "U:lstat", win32_wstat
);
5759 return posix_do_stat(self
, args
, "et:lstat", STAT
, NULL
, NULL
);
5761 #endif /* !HAVE_LSTAT */
5765 #ifdef HAVE_READLINK
5766 PyDoc_STRVAR(posix_readlink__doc__
,
5767 "readlink(path) -> path\n\n\
5768 Return a string representing the path to which the symbolic link points.");
5771 posix_readlink(PyObject
*self
, PyObject
*args
)
5774 char buf
[MAXPATHLEN
];
5777 #ifdef Py_USING_UNICODE
5778 int arg_is_unicode
= 0;
5781 if (!PyArg_ParseTuple(args
, "et:readlink",
5782 Py_FileSystemDefaultEncoding
, &path
))
5784 #ifdef Py_USING_UNICODE
5785 v
= PySequence_GetItem(args
, 0);
5791 if (PyUnicode_Check(v
)) {
5797 Py_BEGIN_ALLOW_THREADS
5798 n
= readlink(path
, buf
, (int) sizeof buf
);
5799 Py_END_ALLOW_THREADS
5801 return posix_error_with_allocated_filename(path
);
5804 v
= PyString_FromStringAndSize(buf
, n
);
5805 #ifdef Py_USING_UNICODE
5806 if (arg_is_unicode
) {
5809 w
= PyUnicode_FromEncodedObject(v
,
5810 Py_FileSystemDefaultEncoding
,
5817 /* fall back to the original byte string, as
5818 discussed in patch #683592 */
5825 #endif /* HAVE_READLINK */
5829 PyDoc_STRVAR(posix_symlink__doc__
,
5830 "symlink(src, dst)\n\n\
5831 Create a symbolic link pointing to src named dst.");
5834 posix_symlink(PyObject
*self
, PyObject
*args
)
5836 return posix_2str(args
, "etet:symlink", symlink
);
5838 #endif /* HAVE_SYMLINK */
5843 #define HZ 60 /* Universal constant :-) */
5846 #if defined(PYCC_VACPP) && defined(PYOS_OS2)
5852 Py_BEGIN_ALLOW_THREADS
5853 DosQuerySysInfo(QSV_MS_COUNT
, QSV_MS_COUNT
, &value
, sizeof(value
));
5854 Py_END_ALLOW_THREADS
5860 posix_times(PyObject
*self
, PyObject
*noargs
)
5862 /* Currently Only Uptime is Provided -- Others Later */
5863 return Py_BuildValue("ddddd",
5864 (double)0 /* t.tms_utime / HZ */,
5865 (double)0 /* t.tms_stime / HZ */,
5866 (double)0 /* t.tms_cutime / HZ */,
5867 (double)0 /* t.tms_cstime / HZ */,
5868 (double)system_uptime() / 1000);
5872 posix_times(PyObject
*self
, PyObject
*noargs
)
5878 if (c
== (clock_t) -1)
5879 return posix_error();
5880 return Py_BuildValue("ddddd",
5881 (double)t
.tms_utime
/ HZ
,
5882 (double)t
.tms_stime
/ HZ
,
5883 (double)t
.tms_cutime
/ HZ
,
5884 (double)t
.tms_cstime
/ HZ
,
5887 #endif /* not OS2 */
5888 #endif /* HAVE_TIMES */
5892 #define HAVE_TIMES /* so the method table will pick it up */
5894 posix_times(PyObject
*self
, PyObject
*noargs
)
5896 FILETIME create
, exit
, kernel
, user
;
5898 hProc
= GetCurrentProcess();
5899 GetProcessTimes(hProc
, &create
, &exit
, &kernel
, &user
);
5900 /* The fields of a FILETIME structure are the hi and lo part
5901 of a 64-bit value expressed in 100 nanosecond units.
5902 1e7 is one second in such units; 1e-7 the inverse.
5903 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
5905 return Py_BuildValue(
5907 (double)(kernel
.dwHighDateTime
*429.4967296 +
5908 kernel
.dwLowDateTime
*1e-7),
5909 (double)(user
.dwHighDateTime
*429.4967296 +
5910 user
.dwLowDateTime
*1e-7),
5915 #endif /* MS_WINDOWS */
5918 PyDoc_STRVAR(posix_times__doc__
,
5919 "times() -> (utime, stime, cutime, cstime, elapsed_time)\n\n\
5920 Return a tuple of floating point numbers indicating process times.");
5925 PyDoc_STRVAR(posix_getsid__doc__
,
5926 "getsid(pid) -> sid\n\n\
5927 Call the system call getsid().");
5930 posix_getsid(PyObject
*self
, PyObject
*args
)
5933 if (!PyArg_ParseTuple(args
, "i:getsid", &pid
))
5937 return posix_error();
5938 return PyInt_FromLong((long)sid
);
5940 #endif /* HAVE_GETSID */
5944 PyDoc_STRVAR(posix_setsid__doc__
,
5946 Call the system call setsid().");
5949 posix_setsid(PyObject
*self
, PyObject
*noargs
)
5952 return posix_error();
5956 #endif /* HAVE_SETSID */
5959 PyDoc_STRVAR(posix_setpgid__doc__
,
5960 "setpgid(pid, pgrp)\n\n\
5961 Call the system call setpgid().");
5964 posix_setpgid(PyObject
*self
, PyObject
*args
)
5967 if (!PyArg_ParseTuple(args
, "ii:setpgid", &pid
, &pgrp
))
5969 if (setpgid(pid
, pgrp
) < 0)
5970 return posix_error();
5974 #endif /* HAVE_SETPGID */
5977 #ifdef HAVE_TCGETPGRP
5978 PyDoc_STRVAR(posix_tcgetpgrp__doc__
,
5979 "tcgetpgrp(fd) -> pgid\n\n\
5980 Return the process group associated with the terminal given by a fd.");
5983 posix_tcgetpgrp(PyObject
*self
, PyObject
*args
)
5986 if (!PyArg_ParseTuple(args
, "i:tcgetpgrp", &fd
))
5988 pgid
= tcgetpgrp(fd
);
5990 return posix_error();
5991 return PyInt_FromLong((long)pgid
);
5993 #endif /* HAVE_TCGETPGRP */
5996 #ifdef HAVE_TCSETPGRP
5997 PyDoc_STRVAR(posix_tcsetpgrp__doc__
,
5998 "tcsetpgrp(fd, pgid)\n\n\
5999 Set the process group associated with the terminal given by a fd.");
6002 posix_tcsetpgrp(PyObject
*self
, PyObject
*args
)
6005 if (!PyArg_ParseTuple(args
, "ii:tcsetpgrp", &fd
, &pgid
))
6007 if (tcsetpgrp(fd
, pgid
) < 0)
6008 return posix_error();
6012 #endif /* HAVE_TCSETPGRP */
6014 /* Functions acting on file descriptors */
6016 PyDoc_STRVAR(posix_open__doc__
,
6017 "open(filename, flag [, mode=0777]) -> fd\n\n\
6018 Open a file (for low level IO).");
6021 posix_open(PyObject
*self
, PyObject
*args
)
6029 if (unicode_file_names()) {
6030 PyUnicodeObject
*po
;
6031 if (PyArg_ParseTuple(args
, "Ui|i:mkdir", &po
, &flag
, &mode
)) {
6032 Py_BEGIN_ALLOW_THREADS
6033 /* PyUnicode_AS_UNICODE OK without thread
6034 lock as it is a simple dereference. */
6035 fd
= _wopen(PyUnicode_AS_UNICODE(po
), flag
, mode
);
6036 Py_END_ALLOW_THREADS
6038 return posix_error();
6039 return PyInt_FromLong((long)fd
);
6041 /* Drop the argument parsing error as narrow strings
6047 if (!PyArg_ParseTuple(args
, "eti|i",
6048 Py_FileSystemDefaultEncoding
, &file
,
6052 Py_BEGIN_ALLOW_THREADS
6053 fd
= open(file
, flag
, mode
);
6054 Py_END_ALLOW_THREADS
6056 return posix_error_with_allocated_filename(file
);
6058 return PyInt_FromLong((long)fd
);
6062 PyDoc_STRVAR(posix_close__doc__
,
6064 Close a file descriptor (for low level IO).");
6067 posix_close(PyObject
*self
, PyObject
*args
)
6070 if (!PyArg_ParseTuple(args
, "i:close", &fd
))
6072 Py_BEGIN_ALLOW_THREADS
6074 Py_END_ALLOW_THREADS
6076 return posix_error();
6082 PyDoc_STRVAR(posix_dup__doc__
,
6083 "dup(fd) -> fd2\n\n\
6084 Return a duplicate of a file descriptor.");
6087 posix_dup(PyObject
*self
, PyObject
*args
)
6090 if (!PyArg_ParseTuple(args
, "i:dup", &fd
))
6092 Py_BEGIN_ALLOW_THREADS
6094 Py_END_ALLOW_THREADS
6096 return posix_error();
6097 return PyInt_FromLong((long)fd
);
6101 PyDoc_STRVAR(posix_dup2__doc__
,
6102 "dup2(old_fd, new_fd)\n\n\
6103 Duplicate file descriptor.");
6106 posix_dup2(PyObject
*self
, PyObject
*args
)
6109 if (!PyArg_ParseTuple(args
, "ii:dup2", &fd
, &fd2
))
6111 Py_BEGIN_ALLOW_THREADS
6112 res
= dup2(fd
, fd2
);
6113 Py_END_ALLOW_THREADS
6115 return posix_error();
6121 PyDoc_STRVAR(posix_lseek__doc__
,
6122 "lseek(fd, pos, how) -> newpos\n\n\
6123 Set the current position of a file descriptor.");
6126 posix_lseek(PyObject
*self
, PyObject
*args
)
6129 #if defined(MS_WIN64) || defined(MS_WINDOWS)
6130 PY_LONG_LONG pos
, res
;
6135 if (!PyArg_ParseTuple(args
, "iOi:lseek", &fd
, &posobj
, &how
))
6138 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
6140 case 0: how
= SEEK_SET
; break;
6141 case 1: how
= SEEK_CUR
; break;
6142 case 2: how
= SEEK_END
; break;
6144 #endif /* SEEK_END */
6146 #if !defined(HAVE_LARGEFILE_SUPPORT)
6147 pos
= PyInt_AsLong(posobj
);
6149 pos
= PyLong_Check(posobj
) ?
6150 PyLong_AsLongLong(posobj
) : PyInt_AsLong(posobj
);
6152 if (PyErr_Occurred())
6155 Py_BEGIN_ALLOW_THREADS
6156 #if defined(MS_WIN64) || defined(MS_WINDOWS)
6157 res
= _lseeki64(fd
, pos
, how
);
6159 res
= lseek(fd
, pos
, how
);
6161 Py_END_ALLOW_THREADS
6163 return posix_error();
6165 #if !defined(HAVE_LARGEFILE_SUPPORT)
6166 return PyInt_FromLong(res
);
6168 return PyLong_FromLongLong(res
);
6173 PyDoc_STRVAR(posix_read__doc__
,
6174 "read(fd, buffersize) -> string\n\n\
6175 Read a file descriptor.");
6178 posix_read(PyObject
*self
, PyObject
*args
)
6182 if (!PyArg_ParseTuple(args
, "ii:read", &fd
, &size
))
6186 return posix_error();
6188 buffer
= PyString_FromStringAndSize((char *)NULL
, size
);
6191 Py_BEGIN_ALLOW_THREADS
6192 n
= read(fd
, PyString_AsString(buffer
), size
);
6193 Py_END_ALLOW_THREADS
6196 return posix_error();
6199 _PyString_Resize(&buffer
, n
);
6204 PyDoc_STRVAR(posix_write__doc__
,
6205 "write(fd, string) -> byteswritten\n\n\
6206 Write a string to a file descriptor.");
6209 posix_write(PyObject
*self
, PyObject
*args
)
6215 if (!PyArg_ParseTuple(args
, "is#:write", &fd
, &buffer
, &size
))
6217 Py_BEGIN_ALLOW_THREADS
6218 size
= write(fd
, buffer
, (size_t)size
);
6219 Py_END_ALLOW_THREADS
6221 return posix_error();
6222 return PyInt_FromSsize_t(size
);
6226 PyDoc_STRVAR(posix_fstat__doc__
,
6227 "fstat(fd) -> stat result\n\n\
6228 Like stat(), but for an open file descriptor.");
6231 posix_fstat(PyObject
*self
, PyObject
*args
)
6236 if (!PyArg_ParseTuple(args
, "i:fstat", &fd
))
6239 /* on OpenVMS we must ensure that all bytes are written to the file */
6242 Py_BEGIN_ALLOW_THREADS
6243 res
= FSTAT(fd
, &st
);
6244 Py_END_ALLOW_THREADS
6247 return win32_error("fstat", NULL
);
6249 return posix_error();
6253 return _pystat_fromstructstat(&st
);
6257 PyDoc_STRVAR(posix_fdopen__doc__
,
6258 "fdopen(fd [, mode='r' [, bufsize]]) -> file_object\n\n\
6259 Return an open file object connected to a file descriptor.");
6262 posix_fdopen(PyObject
*self
, PyObject
*args
)
6265 char *orgmode
= "r";
6270 if (!PyArg_ParseTuple(args
, "i|si", &fd
, &orgmode
, &bufsize
))
6273 /* Sanitize mode. See fileobject.c */
6274 mode
= PyMem_MALLOC(strlen(orgmode
)+3);
6279 strcpy(mode
, orgmode
);
6280 if (_PyFile_SanitizeMode(mode
)) {
6284 Py_BEGIN_ALLOW_THREADS
6285 #if !defined(MS_WINDOWS) && defined(HAVE_FCNTL_H)
6286 if (mode
[0] == 'a') {
6287 /* try to make sure the O_APPEND flag is set */
6289 flags
= fcntl(fd
, F_GETFL
);
6291 fcntl(fd
, F_SETFL
, flags
| O_APPEND
);
6292 fp
= fdopen(fd
, mode
);
6293 if (fp
== NULL
&& flags
!= -1)
6294 /* restore old mode if fdopen failed */
6295 fcntl(fd
, F_SETFL
, flags
);
6297 fp
= fdopen(fd
, mode
);
6300 fp
= fdopen(fd
, mode
);
6302 Py_END_ALLOW_THREADS
6305 return posix_error();
6306 f
= PyFile_FromFile(fp
, "<fdopen>", orgmode
, fclose
);
6308 PyFile_SetBufSize(f
, bufsize
);
6312 PyDoc_STRVAR(posix_isatty__doc__
,
6313 "isatty(fd) -> bool\n\n\
6314 Return True if the file descriptor 'fd' is an open file descriptor\n\
6315 connected to the slave end of a terminal.");
6318 posix_isatty(PyObject
*self
, PyObject
*args
)
6321 if (!PyArg_ParseTuple(args
, "i:isatty", &fd
))
6323 return PyBool_FromLong(isatty(fd
));
6327 PyDoc_STRVAR(posix_pipe__doc__
,
6328 "pipe() -> (read_end, write_end)\n\n\
6332 posix_pipe(PyObject
*self
, PyObject
*noargs
)
6334 #if defined(PYOS_OS2)
6338 Py_BEGIN_ALLOW_THREADS
6339 rc
= DosCreatePipe( &read
, &write
, 4096);
6340 Py_END_ALLOW_THREADS
6342 return os2_error(rc
);
6344 return Py_BuildValue("(ii)", read
, write
);
6346 #if !defined(MS_WINDOWS)
6349 Py_BEGIN_ALLOW_THREADS
6351 Py_END_ALLOW_THREADS
6353 return posix_error();
6354 return Py_BuildValue("(ii)", fds
[0], fds
[1]);
6355 #else /* MS_WINDOWS */
6357 int read_fd
, write_fd
;
6359 Py_BEGIN_ALLOW_THREADS
6360 ok
= CreatePipe(&read
, &write
, NULL
, 0);
6361 Py_END_ALLOW_THREADS
6363 return win32_error("CreatePipe", NULL
);
6364 read_fd
= _open_osfhandle((Py_intptr_t
)read
, 0);
6365 write_fd
= _open_osfhandle((Py_intptr_t
)write
, 1);
6366 return Py_BuildValue("(ii)", read_fd
, write_fd
);
6367 #endif /* MS_WINDOWS */
6370 #endif /* HAVE_PIPE */
6374 PyDoc_STRVAR(posix_mkfifo__doc__
,
6375 "mkfifo(filename [, mode=0666])\n\n\
6376 Create a FIFO (a POSIX named pipe).");
6379 posix_mkfifo(PyObject
*self
, PyObject
*args
)
6384 if (!PyArg_ParseTuple(args
, "s|i:mkfifo", &filename
, &mode
))
6386 Py_BEGIN_ALLOW_THREADS
6387 res
= mkfifo(filename
, mode
);
6388 Py_END_ALLOW_THREADS
6390 return posix_error();
6397 #if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
6398 PyDoc_STRVAR(posix_mknod__doc__
,
6399 "mknod(filename [, mode=0600, device])\n\n\
6400 Create a filesystem node (file, device special file or named pipe)\n\
6401 named filename. mode specifies both the permissions to use and the\n\
6402 type of node to be created, being combined (bitwise OR) with one of\n\
6403 S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. For S_IFCHR and S_IFBLK,\n\
6404 device defines the newly created device special file (probably using\n\
6405 os.makedev()), otherwise it is ignored.");
6409 posix_mknod(PyObject
*self
, PyObject
*args
)
6415 if (!PyArg_ParseTuple(args
, "s|ii:mknod", &filename
, &mode
, &device
))
6417 Py_BEGIN_ALLOW_THREADS
6418 res
= mknod(filename
, mode
, device
);
6419 Py_END_ALLOW_THREADS
6421 return posix_error();
6427 #ifdef HAVE_DEVICE_MACROS
6428 PyDoc_STRVAR(posix_major__doc__
,
6429 "major(device) -> major number\n\
6430 Extracts a device major number from a raw device number.");
6433 posix_major(PyObject
*self
, PyObject
*args
)
6436 if (!PyArg_ParseTuple(args
, "i:major", &device
))
6438 return PyInt_FromLong((long)major(device
));
6441 PyDoc_STRVAR(posix_minor__doc__
,
6442 "minor(device) -> minor number\n\
6443 Extracts a device minor number from a raw device number.");
6446 posix_minor(PyObject
*self
, PyObject
*args
)
6449 if (!PyArg_ParseTuple(args
, "i:minor", &device
))
6451 return PyInt_FromLong((long)minor(device
));
6454 PyDoc_STRVAR(posix_makedev__doc__
,
6455 "makedev(major, minor) -> device number\n\
6456 Composes a raw device number from the major and minor device numbers.");
6459 posix_makedev(PyObject
*self
, PyObject
*args
)
6462 if (!PyArg_ParseTuple(args
, "ii:makedev", &major
, &minor
))
6464 return PyInt_FromLong((long)makedev(major
, minor
));
6466 #endif /* device macros */
6469 #ifdef HAVE_FTRUNCATE
6470 PyDoc_STRVAR(posix_ftruncate__doc__
,
6471 "ftruncate(fd, length)\n\n\
6472 Truncate a file to a specified length.");
6475 posix_ftruncate(PyObject
*self
, PyObject
*args
)
6482 if (!PyArg_ParseTuple(args
, "iO:ftruncate", &fd
, &lenobj
))
6485 #if !defined(HAVE_LARGEFILE_SUPPORT)
6486 length
= PyInt_AsLong(lenobj
);
6488 length
= PyLong_Check(lenobj
) ?
6489 PyLong_AsLongLong(lenobj
) : PyInt_AsLong(lenobj
);
6491 if (PyErr_Occurred())
6494 Py_BEGIN_ALLOW_THREADS
6495 res
= ftruncate(fd
, length
);
6496 Py_END_ALLOW_THREADS
6498 PyErr_SetFromErrno(PyExc_IOError
);
6507 PyDoc_STRVAR(posix_putenv__doc__
,
6508 "putenv(key, value)\n\n\
6509 Change or add an environment variable.");
6511 /* Save putenv() parameters as values here, so we can collect them when they
6512 * get re-set with another call for the same key. */
6513 static PyObject
*posix_putenv_garbage
;
6516 posix_putenv(PyObject
*self
, PyObject
*args
)
6523 if (!PyArg_ParseTuple(args
, "ss:putenv", &s1
, &s2
))
6526 #if defined(PYOS_OS2)
6527 if (stricmp(s1
, "BEGINLIBPATH") == 0) {
6530 rc
= DosSetExtLIBPATH(s2
, BEGIN_LIBPATH
);
6532 return os2_error(rc
);
6534 } else if (stricmp(s1
, "ENDLIBPATH") == 0) {
6537 rc
= DosSetExtLIBPATH(s2
, END_LIBPATH
);
6539 return os2_error(rc
);
6543 /* XXX This can leak memory -- not easy to fix :-( */
6544 len
= strlen(s1
) + strlen(s2
) + 2;
6545 /* len includes space for a trailing \0; the size arg to
6546 PyString_FromStringAndSize does not count that */
6547 newstr
= PyString_FromStringAndSize(NULL
, (int)len
- 1);
6549 return PyErr_NoMemory();
6550 newenv
= PyString_AS_STRING(newstr
);
6551 PyOS_snprintf(newenv
, len
, "%s=%s", s1
, s2
);
6552 if (putenv(newenv
)) {
6557 /* Install the first arg and newstr in posix_putenv_garbage;
6558 * this will cause previous value to be collected. This has to
6559 * happen after the real putenv() call because the old value
6560 * was still accessible until then. */
6561 if (PyDict_SetItem(posix_putenv_garbage
,
6562 PyTuple_GET_ITEM(args
, 0), newstr
)) {
6563 /* really not much we can do; just leak */
6570 #if defined(PYOS_OS2)
6578 #ifdef HAVE_UNSETENV
6579 PyDoc_STRVAR(posix_unsetenv__doc__
,
6581 Delete an environment variable.");
6584 posix_unsetenv(PyObject
*self
, PyObject
*args
)
6588 if (!PyArg_ParseTuple(args
, "s:unsetenv", &s1
))
6593 /* Remove the key from posix_putenv_garbage;
6594 * this will cause it to be collected. This has to
6595 * happen after the real unsetenv() call because the
6596 * old value was still accessible until then.
6598 if (PyDict_DelItem(posix_putenv_garbage
,
6599 PyTuple_GET_ITEM(args
, 0))) {
6600 /* really not much we can do; just leak */
6607 #endif /* unsetenv */
6609 #ifdef HAVE_STRERROR
6610 PyDoc_STRVAR(posix_strerror__doc__
,
6611 "strerror(code) -> string\n\n\
6612 Translate an error code to a message string.");
6615 posix_strerror(PyObject
*self
, PyObject
*args
)
6619 if (!PyArg_ParseTuple(args
, "i:strerror", &code
))
6621 message
= strerror(code
);
6622 if (message
== NULL
) {
6623 PyErr_SetString(PyExc_ValueError
,
6624 "strerror() argument out of range");
6627 return PyString_FromString(message
);
6629 #endif /* strerror */
6632 #ifdef HAVE_SYS_WAIT_H
6635 PyDoc_STRVAR(posix_WCOREDUMP__doc__
,
6636 "WCOREDUMP(status) -> bool\n\n\
6637 Return True if the process returning 'status' was dumped to a core file.");
6640 posix_WCOREDUMP(PyObject
*self
, PyObject
*args
)
6643 WAIT_STATUS_INT(status
) = 0;
6645 if (!PyArg_ParseTuple(args
, "i:WCOREDUMP", &WAIT_STATUS_INT(status
)))
6648 return PyBool_FromLong(WCOREDUMP(status
));
6650 #endif /* WCOREDUMP */
6653 PyDoc_STRVAR(posix_WIFCONTINUED__doc__
,
6654 "WIFCONTINUED(status) -> bool\n\n\
6655 Return True if the process returning 'status' was continued from a\n\
6656 job control stop.");
6659 posix_WIFCONTINUED(PyObject
*self
, PyObject
*args
)
6662 WAIT_STATUS_INT(status
) = 0;
6664 if (!PyArg_ParseTuple(args
, "i:WCONTINUED", &WAIT_STATUS_INT(status
)))
6667 return PyBool_FromLong(WIFCONTINUED(status
));
6669 #endif /* WIFCONTINUED */
6672 PyDoc_STRVAR(posix_WIFSTOPPED__doc__
,
6673 "WIFSTOPPED(status) -> bool\n\n\
6674 Return True if the process returning 'status' was stopped.");
6677 posix_WIFSTOPPED(PyObject
*self
, PyObject
*args
)
6680 WAIT_STATUS_INT(status
) = 0;
6682 if (!PyArg_ParseTuple(args
, "i:WIFSTOPPED", &WAIT_STATUS_INT(status
)))
6685 return PyBool_FromLong(WIFSTOPPED(status
));
6687 #endif /* WIFSTOPPED */
6690 PyDoc_STRVAR(posix_WIFSIGNALED__doc__
,
6691 "WIFSIGNALED(status) -> bool\n\n\
6692 Return True if the process returning 'status' was terminated by a signal.");
6695 posix_WIFSIGNALED(PyObject
*self
, PyObject
*args
)
6698 WAIT_STATUS_INT(status
) = 0;
6700 if (!PyArg_ParseTuple(args
, "i:WIFSIGNALED", &WAIT_STATUS_INT(status
)))
6703 return PyBool_FromLong(WIFSIGNALED(status
));
6705 #endif /* WIFSIGNALED */
6708 PyDoc_STRVAR(posix_WIFEXITED__doc__
,
6709 "WIFEXITED(status) -> bool\n\n\
6710 Return true if the process returning 'status' exited using the exit()\n\
6714 posix_WIFEXITED(PyObject
*self
, PyObject
*args
)
6717 WAIT_STATUS_INT(status
) = 0;
6719 if (!PyArg_ParseTuple(args
, "i:WIFEXITED", &WAIT_STATUS_INT(status
)))
6722 return PyBool_FromLong(WIFEXITED(status
));
6724 #endif /* WIFEXITED */
6727 PyDoc_STRVAR(posix_WEXITSTATUS__doc__
,
6728 "WEXITSTATUS(status) -> integer\n\n\
6729 Return the process return code from 'status'.");
6732 posix_WEXITSTATUS(PyObject
*self
, PyObject
*args
)
6735 WAIT_STATUS_INT(status
) = 0;
6737 if (!PyArg_ParseTuple(args
, "i:WEXITSTATUS", &WAIT_STATUS_INT(status
)))
6740 return Py_BuildValue("i", WEXITSTATUS(status
));
6742 #endif /* WEXITSTATUS */
6745 PyDoc_STRVAR(posix_WTERMSIG__doc__
,
6746 "WTERMSIG(status) -> integer\n\n\
6747 Return the signal that terminated the process that provided the 'status'\n\
6751 posix_WTERMSIG(PyObject
*self
, PyObject
*args
)
6754 WAIT_STATUS_INT(status
) = 0;
6756 if (!PyArg_ParseTuple(args
, "i:WTERMSIG", &WAIT_STATUS_INT(status
)))
6759 return Py_BuildValue("i", WTERMSIG(status
));
6761 #endif /* WTERMSIG */
6764 PyDoc_STRVAR(posix_WSTOPSIG__doc__
,
6765 "WSTOPSIG(status) -> integer\n\n\
6766 Return the signal that stopped the process that provided\n\
6767 the 'status' value.");
6770 posix_WSTOPSIG(PyObject
*self
, PyObject
*args
)
6773 WAIT_STATUS_INT(status
) = 0;
6775 if (!PyArg_ParseTuple(args
, "i:WSTOPSIG", &WAIT_STATUS_INT(status
)))
6778 return Py_BuildValue("i", WSTOPSIG(status
));
6780 #endif /* WSTOPSIG */
6782 #endif /* HAVE_SYS_WAIT_H */
6785 #if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
6787 /* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the
6788 needed definitions in sys/statvfs.h */
6791 #include <sys/statvfs.h>
6794 _pystatvfs_fromstructstatvfs(struct statvfs st
) {
6795 PyObject
*v
= PyStructSequence_New(&StatVFSResultType
);
6799 #if !defined(HAVE_LARGEFILE_SUPPORT)
6800 PyStructSequence_SET_ITEM(v
, 0, PyInt_FromLong((long) st
.f_bsize
));
6801 PyStructSequence_SET_ITEM(v
, 1, PyInt_FromLong((long) st
.f_frsize
));
6802 PyStructSequence_SET_ITEM(v
, 2, PyInt_FromLong((long) st
.f_blocks
));
6803 PyStructSequence_SET_ITEM(v
, 3, PyInt_FromLong((long) st
.f_bfree
));
6804 PyStructSequence_SET_ITEM(v
, 4, PyInt_FromLong((long) st
.f_bavail
));
6805 PyStructSequence_SET_ITEM(v
, 5, PyInt_FromLong((long) st
.f_files
));
6806 PyStructSequence_SET_ITEM(v
, 6, PyInt_FromLong((long) st
.f_ffree
));
6807 PyStructSequence_SET_ITEM(v
, 7, PyInt_FromLong((long) st
.f_favail
));
6808 PyStructSequence_SET_ITEM(v
, 8, PyInt_FromLong((long) st
.f_flag
));
6809 PyStructSequence_SET_ITEM(v
, 9, PyInt_FromLong((long) st
.f_namemax
));
6811 PyStructSequence_SET_ITEM(v
, 0, PyInt_FromLong((long) st
.f_bsize
));
6812 PyStructSequence_SET_ITEM(v
, 1, PyInt_FromLong((long) st
.f_frsize
));
6813 PyStructSequence_SET_ITEM(v
, 2,
6814 PyLong_FromLongLong((PY_LONG_LONG
) st
.f_blocks
));
6815 PyStructSequence_SET_ITEM(v
, 3,
6816 PyLong_FromLongLong((PY_LONG_LONG
) st
.f_bfree
));
6817 PyStructSequence_SET_ITEM(v
, 4,
6818 PyLong_FromLongLong((PY_LONG_LONG
) st
.f_bavail
));
6819 PyStructSequence_SET_ITEM(v
, 5,
6820 PyLong_FromLongLong((PY_LONG_LONG
) st
.f_files
));
6821 PyStructSequence_SET_ITEM(v
, 6,
6822 PyLong_FromLongLong((PY_LONG_LONG
) st
.f_ffree
));
6823 PyStructSequence_SET_ITEM(v
, 7,
6824 PyLong_FromLongLong((PY_LONG_LONG
) st
.f_favail
));
6825 PyStructSequence_SET_ITEM(v
, 8, PyInt_FromLong((long) st
.f_flag
));
6826 PyStructSequence_SET_ITEM(v
, 9, PyInt_FromLong((long) st
.f_namemax
));
6832 PyDoc_STRVAR(posix_fstatvfs__doc__
,
6833 "fstatvfs(fd) -> statvfs result\n\n\
6834 Perform an fstatvfs system call on the given fd.");
6837 posix_fstatvfs(PyObject
*self
, PyObject
*args
)
6842 if (!PyArg_ParseTuple(args
, "i:fstatvfs", &fd
))
6844 Py_BEGIN_ALLOW_THREADS
6845 res
= fstatvfs(fd
, &st
);
6846 Py_END_ALLOW_THREADS
6848 return posix_error();
6850 return _pystatvfs_fromstructstatvfs(st
);
6852 #endif /* HAVE_FSTATVFS && HAVE_SYS_STATVFS_H */
6855 #if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
6856 #include <sys/statvfs.h>
6858 PyDoc_STRVAR(posix_statvfs__doc__
,
6859 "statvfs(path) -> statvfs result\n\n\
6860 Perform a statvfs system call on the given path.");
6863 posix_statvfs(PyObject
*self
, PyObject
*args
)
6868 if (!PyArg_ParseTuple(args
, "s:statvfs", &path
))
6870 Py_BEGIN_ALLOW_THREADS
6871 res
= statvfs(path
, &st
);
6872 Py_END_ALLOW_THREADS
6874 return posix_error_with_filename(path
);
6876 return _pystatvfs_fromstructstatvfs(st
);
6878 #endif /* HAVE_STATVFS */
6882 PyDoc_STRVAR(posix_tempnam__doc__
,
6883 "tempnam([dir[, prefix]]) -> string\n\n\
6884 Return a unique name for a temporary file.\n\
6885 The directory and a prefix may be specified as strings; they may be omitted\n\
6886 or None if not needed.");
6889 posix_tempnam(PyObject
*self
, PyObject
*args
)
6891 PyObject
*result
= NULL
;
6896 if (!PyArg_ParseTuple(args
, "|zz:tempnam", &dir
, &pfx
))
6899 if (PyErr_Warn(PyExc_RuntimeWarning
,
6900 "tempnam is a potential security risk to your program") < 0)
6904 name
= _tempnam(dir
, pfx
);
6906 name
= tempnam(dir
, pfx
);
6909 return PyErr_NoMemory();
6910 result
= PyString_FromString(name
);
6918 PyDoc_STRVAR(posix_tmpfile__doc__
,
6919 "tmpfile() -> file object\n\n\
6920 Create a temporary file with no directory entries.");
6923 posix_tmpfile(PyObject
*self
, PyObject
*noargs
)
6929 return posix_error();
6930 return PyFile_FromFile(fp
, "<tmpfile>", "w+b", fclose
);
6936 PyDoc_STRVAR(posix_tmpnam__doc__
,
6937 "tmpnam() -> string\n\n\
6938 Return a unique name for a temporary file.");
6941 posix_tmpnam(PyObject
*self
, PyObject
*noargs
)
6943 char buffer
[L_tmpnam
];
6946 if (PyErr_Warn(PyExc_RuntimeWarning
,
6947 "tmpnam is a potential security risk to your program") < 0)
6951 name
= tmpnam_r(buffer
);
6953 name
= tmpnam(buffer
);
6956 PyObject
*err
= Py_BuildValue("is", 0,
6958 "unexpected NULL from tmpnam_r"
6960 "unexpected NULL from tmpnam"
6963 PyErr_SetObject(PyExc_OSError
, err
);
6967 return PyString_FromString(buffer
);
6972 /* This is used for fpathconf(), pathconf(), confstr() and sysconf().
6973 * It maps strings representing configuration variable names to
6974 * integer values, allowing those functions to be called with the
6975 * magic names instead of polluting the module's namespace with tons of
6976 * rarely-used constants. There are three separate tables that use
6977 * these definitions.
6979 * This code is always included, even if none of the interfaces that
6980 * need it are included. The #if hackery needed to avoid it would be
6981 * sufficiently pervasive that it's not worth the loss of readability.
6989 conv_confname(PyObject
*arg
, int *valuep
, struct constdef
*table
,
6992 if (PyInt_Check(arg
)) {
6993 *valuep
= PyInt_AS_LONG(arg
);
6996 if (PyString_Check(arg
)) {
6997 /* look up the value in the table using a binary search */
7000 size_t hi
= tablesize
;
7002 char *confname
= PyString_AS_STRING(arg
);
7004 mid
= (lo
+ hi
) / 2;
7005 cmp
= strcmp(confname
, table
[mid
].name
);
7011 *valuep
= table
[mid
].value
;
7015 PyErr_SetString(PyExc_ValueError
, "unrecognized configuration name");
7018 PyErr_SetString(PyExc_TypeError
,
7019 "configuration names must be strings or integers");
7024 #if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
7025 static struct constdef posix_constants_pathconf
[] = {
7026 #ifdef _PC_ABI_AIO_XFER_MAX
7027 {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX
},
7029 #ifdef _PC_ABI_ASYNC_IO
7030 {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO
},
7033 {"PC_ASYNC_IO", _PC_ASYNC_IO
},
7035 #ifdef _PC_CHOWN_RESTRICTED
7036 {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED
},
7038 #ifdef _PC_FILESIZEBITS
7039 {"PC_FILESIZEBITS", _PC_FILESIZEBITS
},
7042 {"PC_LAST", _PC_LAST
},
7045 {"PC_LINK_MAX", _PC_LINK_MAX
},
7047 #ifdef _PC_MAX_CANON
7048 {"PC_MAX_CANON", _PC_MAX_CANON
},
7050 #ifdef _PC_MAX_INPUT
7051 {"PC_MAX_INPUT", _PC_MAX_INPUT
},
7054 {"PC_NAME_MAX", _PC_NAME_MAX
},
7057 {"PC_NO_TRUNC", _PC_NO_TRUNC
},
7060 {"PC_PATH_MAX", _PC_PATH_MAX
},
7063 {"PC_PIPE_BUF", _PC_PIPE_BUF
},
7066 {"PC_PRIO_IO", _PC_PRIO_IO
},
7068 #ifdef _PC_SOCK_MAXBUF
7069 {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF
},
7072 {"PC_SYNC_IO", _PC_SYNC_IO
},
7075 {"PC_VDISABLE", _PC_VDISABLE
},
7080 conv_path_confname(PyObject
*arg
, int *valuep
)
7082 return conv_confname(arg
, valuep
, posix_constants_pathconf
,
7083 sizeof(posix_constants_pathconf
)
7084 / sizeof(struct constdef
));
7088 #ifdef HAVE_FPATHCONF
7089 PyDoc_STRVAR(posix_fpathconf__doc__
,
7090 "fpathconf(fd, name) -> integer\n\n\
7091 Return the configuration limit name for the file descriptor fd.\n\
7092 If there is no limit, return -1.");
7095 posix_fpathconf(PyObject
*self
, PyObject
*args
)
7097 PyObject
*result
= NULL
;
7100 if (PyArg_ParseTuple(args
, "iO&:fpathconf", &fd
,
7101 conv_path_confname
, &name
)) {
7105 limit
= fpathconf(fd
, name
);
7106 if (limit
== -1 && errno
!= 0)
7109 result
= PyInt_FromLong(limit
);
7116 #ifdef HAVE_PATHCONF
7117 PyDoc_STRVAR(posix_pathconf__doc__
,
7118 "pathconf(path, name) -> integer\n\n\
7119 Return the configuration limit name for the file or directory path.\n\
7120 If there is no limit, return -1.");
7123 posix_pathconf(PyObject
*self
, PyObject
*args
)
7125 PyObject
*result
= NULL
;
7129 if (PyArg_ParseTuple(args
, "sO&:pathconf", &path
,
7130 conv_path_confname
, &name
)) {
7134 limit
= pathconf(path
, name
);
7135 if (limit
== -1 && errno
!= 0) {
7136 if (errno
== EINVAL
)
7137 /* could be a path or name problem */
7140 posix_error_with_filename(path
);
7143 result
= PyInt_FromLong(limit
);
7150 static struct constdef posix_constants_confstr
[] = {
7151 #ifdef _CS_ARCHITECTURE
7152 {"CS_ARCHITECTURE", _CS_ARCHITECTURE
},
7155 {"CS_HOSTNAME", _CS_HOSTNAME
},
7157 #ifdef _CS_HW_PROVIDER
7158 {"CS_HW_PROVIDER", _CS_HW_PROVIDER
},
7160 #ifdef _CS_HW_SERIAL
7161 {"CS_HW_SERIAL", _CS_HW_SERIAL
},
7163 #ifdef _CS_INITTAB_NAME
7164 {"CS_INITTAB_NAME", _CS_INITTAB_NAME
},
7166 #ifdef _CS_LFS64_CFLAGS
7167 {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS
},
7169 #ifdef _CS_LFS64_LDFLAGS
7170 {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS
},
7172 #ifdef _CS_LFS64_LIBS
7173 {"CS_LFS64_LIBS", _CS_LFS64_LIBS
},
7175 #ifdef _CS_LFS64_LINTFLAGS
7176 {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS
},
7178 #ifdef _CS_LFS_CFLAGS
7179 {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS
},
7181 #ifdef _CS_LFS_LDFLAGS
7182 {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS
},
7185 {"CS_LFS_LIBS", _CS_LFS_LIBS
},
7187 #ifdef _CS_LFS_LINTFLAGS
7188 {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS
},
7191 {"CS_MACHINE", _CS_MACHINE
},
7194 {"CS_PATH", _CS_PATH
},
7197 {"CS_RELEASE", _CS_RELEASE
},
7199 #ifdef _CS_SRPC_DOMAIN
7200 {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN
},
7203 {"CS_SYSNAME", _CS_SYSNAME
},
7206 {"CS_VERSION", _CS_VERSION
},
7208 #ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
7209 {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS
},
7211 #ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
7212 {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS
},
7214 #ifdef _CS_XBS5_ILP32_OFF32_LIBS
7215 {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS
},
7217 #ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
7218 {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS
},
7220 #ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
7221 {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS
},
7223 #ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
7224 {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS
},
7226 #ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
7227 {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS
},
7229 #ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
7230 {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
},
7232 #ifdef _CS_XBS5_LP64_OFF64_CFLAGS
7233 {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS
},
7235 #ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
7236 {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS
},
7238 #ifdef _CS_XBS5_LP64_OFF64_LIBS
7239 {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS
},
7241 #ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
7242 {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS
},
7244 #ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
7245 {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS
},
7247 #ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
7248 {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
},
7250 #ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
7251 {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS
},
7253 #ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
7254 {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
},
7256 #ifdef _MIPS_CS_AVAIL_PROCESSORS
7257 {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS
},
7259 #ifdef _MIPS_CS_BASE
7260 {"MIPS_CS_BASE", _MIPS_CS_BASE
},
7262 #ifdef _MIPS_CS_HOSTID
7263 {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID
},
7265 #ifdef _MIPS_CS_HW_NAME
7266 {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME
},
7268 #ifdef _MIPS_CS_NUM_PROCESSORS
7269 {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS
},
7271 #ifdef _MIPS_CS_OSREL_MAJ
7272 {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ
},
7274 #ifdef _MIPS_CS_OSREL_MIN
7275 {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN
},
7277 #ifdef _MIPS_CS_OSREL_PATCH
7278 {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH
},
7280 #ifdef _MIPS_CS_OS_NAME
7281 {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME
},
7283 #ifdef _MIPS_CS_OS_PROVIDER
7284 {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER
},
7286 #ifdef _MIPS_CS_PROCESSORS
7287 {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS
},
7289 #ifdef _MIPS_CS_SERIAL
7290 {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL
},
7292 #ifdef _MIPS_CS_VENDOR
7293 {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR
},
7298 conv_confstr_confname(PyObject
*arg
, int *valuep
)
7300 return conv_confname(arg
, valuep
, posix_constants_confstr
,
7301 sizeof(posix_constants_confstr
)
7302 / sizeof(struct constdef
));
7305 PyDoc_STRVAR(posix_confstr__doc__
,
7306 "confstr(name) -> string\n\n\
7307 Return a string-valued system configuration variable.");
7310 posix_confstr(PyObject
*self
, PyObject
*args
)
7312 PyObject
*result
= NULL
;
7316 if (PyArg_ParseTuple(args
, "O&:confstr", conv_confstr_confname
, &name
)) {
7320 len
= confstr(name
, buffer
, sizeof(buffer
));
7331 if ((unsigned int)len
>= sizeof(buffer
)) {
7332 result
= PyString_FromStringAndSize(NULL
, len
-1);
7334 confstr(name
, PyString_AS_STRING(result
), len
);
7337 result
= PyString_FromStringAndSize(buffer
, len
-1);
7346 static struct constdef posix_constants_sysconf
[] = {
7347 #ifdef _SC_2_CHAR_TERM
7348 {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM
},
7351 {"SC_2_C_BIND", _SC_2_C_BIND
},
7354 {"SC_2_C_DEV", _SC_2_C_DEV
},
7356 #ifdef _SC_2_C_VERSION
7357 {"SC_2_C_VERSION", _SC_2_C_VERSION
},
7359 #ifdef _SC_2_FORT_DEV
7360 {"SC_2_FORT_DEV", _SC_2_FORT_DEV
},
7362 #ifdef _SC_2_FORT_RUN
7363 {"SC_2_FORT_RUN", _SC_2_FORT_RUN
},
7365 #ifdef _SC_2_LOCALEDEF
7366 {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF
},
7369 {"SC_2_SW_DEV", _SC_2_SW_DEV
},
7372 {"SC_2_UPE", _SC_2_UPE
},
7374 #ifdef _SC_2_VERSION
7375 {"SC_2_VERSION", _SC_2_VERSION
},
7377 #ifdef _SC_ABI_ASYNCHRONOUS_IO
7378 {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO
},
7381 {"SC_ACL", _SC_ACL
},
7383 #ifdef _SC_AIO_LISTIO_MAX
7384 {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX
},
7387 {"SC_AIO_MAX", _SC_AIO_MAX
},
7389 #ifdef _SC_AIO_PRIO_DELTA_MAX
7390 {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX
},
7393 {"SC_ARG_MAX", _SC_ARG_MAX
},
7395 #ifdef _SC_ASYNCHRONOUS_IO
7396 {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO
},
7398 #ifdef _SC_ATEXIT_MAX
7399 {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX
},
7402 {"SC_AUDIT", _SC_AUDIT
},
7404 #ifdef _SC_AVPHYS_PAGES
7405 {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES
},
7407 #ifdef _SC_BC_BASE_MAX
7408 {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX
},
7410 #ifdef _SC_BC_DIM_MAX
7411 {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX
},
7413 #ifdef _SC_BC_SCALE_MAX
7414 {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX
},
7416 #ifdef _SC_BC_STRING_MAX
7417 {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX
},
7420 {"SC_CAP", _SC_CAP
},
7422 #ifdef _SC_CHARCLASS_NAME_MAX
7423 {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX
},
7426 {"SC_CHAR_BIT", _SC_CHAR_BIT
},
7429 {"SC_CHAR_MAX", _SC_CHAR_MAX
},
7432 {"SC_CHAR_MIN", _SC_CHAR_MIN
},
7434 #ifdef _SC_CHILD_MAX
7435 {"SC_CHILD_MAX", _SC_CHILD_MAX
},
7438 {"SC_CLK_TCK", _SC_CLK_TCK
},
7440 #ifdef _SC_COHER_BLKSZ
7441 {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ
},
7443 #ifdef _SC_COLL_WEIGHTS_MAX
7444 {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX
},
7446 #ifdef _SC_DCACHE_ASSOC
7447 {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC
},
7449 #ifdef _SC_DCACHE_BLKSZ
7450 {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ
},
7452 #ifdef _SC_DCACHE_LINESZ
7453 {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ
},
7455 #ifdef _SC_DCACHE_SZ
7456 {"SC_DCACHE_SZ", _SC_DCACHE_SZ
},
7458 #ifdef _SC_DCACHE_TBLKSZ
7459 {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ
},
7461 #ifdef _SC_DELAYTIMER_MAX
7462 {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX
},
7464 #ifdef _SC_EQUIV_CLASS_MAX
7465 {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX
},
7467 #ifdef _SC_EXPR_NEST_MAX
7468 {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX
},
7471 {"SC_FSYNC", _SC_FSYNC
},
7473 #ifdef _SC_GETGR_R_SIZE_MAX
7474 {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX
},
7476 #ifdef _SC_GETPW_R_SIZE_MAX
7477 {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX
},
7479 #ifdef _SC_ICACHE_ASSOC
7480 {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC
},
7482 #ifdef _SC_ICACHE_BLKSZ
7483 {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ
},
7485 #ifdef _SC_ICACHE_LINESZ
7486 {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ
},
7488 #ifdef _SC_ICACHE_SZ
7489 {"SC_ICACHE_SZ", _SC_ICACHE_SZ
},
7492 {"SC_INF", _SC_INF
},
7495 {"SC_INT_MAX", _SC_INT_MAX
},
7498 {"SC_INT_MIN", _SC_INT_MIN
},
7501 {"SC_IOV_MAX", _SC_IOV_MAX
},
7503 #ifdef _SC_IP_SECOPTS
7504 {"SC_IP_SECOPTS", _SC_IP_SECOPTS
},
7506 #ifdef _SC_JOB_CONTROL
7507 {"SC_JOB_CONTROL", _SC_JOB_CONTROL
},
7509 #ifdef _SC_KERN_POINTERS
7510 {"SC_KERN_POINTERS", _SC_KERN_POINTERS
},
7513 {"SC_KERN_SIM", _SC_KERN_SIM
},
7516 {"SC_LINE_MAX", _SC_LINE_MAX
},
7518 #ifdef _SC_LOGIN_NAME_MAX
7519 {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX
},
7521 #ifdef _SC_LOGNAME_MAX
7522 {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX
},
7525 {"SC_LONG_BIT", _SC_LONG_BIT
},
7528 {"SC_MAC", _SC_MAC
},
7530 #ifdef _SC_MAPPED_FILES
7531 {"SC_MAPPED_FILES", _SC_MAPPED_FILES
},
7534 {"SC_MAXPID", _SC_MAXPID
},
7536 #ifdef _SC_MB_LEN_MAX
7537 {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX
},
7540 {"SC_MEMLOCK", _SC_MEMLOCK
},
7542 #ifdef _SC_MEMLOCK_RANGE
7543 {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE
},
7545 #ifdef _SC_MEMORY_PROTECTION
7546 {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION
},
7548 #ifdef _SC_MESSAGE_PASSING
7549 {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING
},
7551 #ifdef _SC_MMAP_FIXED_ALIGNMENT
7552 {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT
},
7554 #ifdef _SC_MQ_OPEN_MAX
7555 {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX
},
7557 #ifdef _SC_MQ_PRIO_MAX
7558 {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX
},
7560 #ifdef _SC_NACLS_MAX
7561 {"SC_NACLS_MAX", _SC_NACLS_MAX
},
7563 #ifdef _SC_NGROUPS_MAX
7564 {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX
},
7566 #ifdef _SC_NL_ARGMAX
7567 {"SC_NL_ARGMAX", _SC_NL_ARGMAX
},
7569 #ifdef _SC_NL_LANGMAX
7570 {"SC_NL_LANGMAX", _SC_NL_LANGMAX
},
7572 #ifdef _SC_NL_MSGMAX
7573 {"SC_NL_MSGMAX", _SC_NL_MSGMAX
},
7576 {"SC_NL_NMAX", _SC_NL_NMAX
},
7578 #ifdef _SC_NL_SETMAX
7579 {"SC_NL_SETMAX", _SC_NL_SETMAX
},
7581 #ifdef _SC_NL_TEXTMAX
7582 {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX
},
7584 #ifdef _SC_NPROCESSORS_CONF
7585 {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF
},
7587 #ifdef _SC_NPROCESSORS_ONLN
7588 {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN
},
7590 #ifdef _SC_NPROC_CONF
7591 {"SC_NPROC_CONF", _SC_NPROC_CONF
},
7593 #ifdef _SC_NPROC_ONLN
7594 {"SC_NPROC_ONLN", _SC_NPROC_ONLN
},
7597 {"SC_NZERO", _SC_NZERO
},
7600 {"SC_OPEN_MAX", _SC_OPEN_MAX
},
7603 {"SC_PAGESIZE", _SC_PAGESIZE
},
7605 #ifdef _SC_PAGE_SIZE
7606 {"SC_PAGE_SIZE", _SC_PAGE_SIZE
},
7609 {"SC_PASS_MAX", _SC_PASS_MAX
},
7611 #ifdef _SC_PHYS_PAGES
7612 {"SC_PHYS_PAGES", _SC_PHYS_PAGES
},
7615 {"SC_PII", _SC_PII
},
7617 #ifdef _SC_PII_INTERNET
7618 {"SC_PII_INTERNET", _SC_PII_INTERNET
},
7620 #ifdef _SC_PII_INTERNET_DGRAM
7621 {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM
},
7623 #ifdef _SC_PII_INTERNET_STREAM
7624 {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM
},
7627 {"SC_PII_OSI", _SC_PII_OSI
},
7629 #ifdef _SC_PII_OSI_CLTS
7630 {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS
},
7632 #ifdef _SC_PII_OSI_COTS
7633 {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS
},
7635 #ifdef _SC_PII_OSI_M
7636 {"SC_PII_OSI_M", _SC_PII_OSI_M
},
7638 #ifdef _SC_PII_SOCKET
7639 {"SC_PII_SOCKET", _SC_PII_SOCKET
},
7642 {"SC_PII_XTI", _SC_PII_XTI
},
7645 {"SC_POLL", _SC_POLL
},
7647 #ifdef _SC_PRIORITIZED_IO
7648 {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO
},
7650 #ifdef _SC_PRIORITY_SCHEDULING
7651 {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING
},
7653 #ifdef _SC_REALTIME_SIGNALS
7654 {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS
},
7656 #ifdef _SC_RE_DUP_MAX
7657 {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX
},
7659 #ifdef _SC_RTSIG_MAX
7660 {"SC_RTSIG_MAX", _SC_RTSIG_MAX
},
7662 #ifdef _SC_SAVED_IDS
7663 {"SC_SAVED_IDS", _SC_SAVED_IDS
},
7665 #ifdef _SC_SCHAR_MAX
7666 {"SC_SCHAR_MAX", _SC_SCHAR_MAX
},
7668 #ifdef _SC_SCHAR_MIN
7669 {"SC_SCHAR_MIN", _SC_SCHAR_MIN
},
7672 {"SC_SELECT", _SC_SELECT
},
7674 #ifdef _SC_SEMAPHORES
7675 {"SC_SEMAPHORES", _SC_SEMAPHORES
},
7677 #ifdef _SC_SEM_NSEMS_MAX
7678 {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX
},
7680 #ifdef _SC_SEM_VALUE_MAX
7681 {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX
},
7683 #ifdef _SC_SHARED_MEMORY_OBJECTS
7684 {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS
},
7687 {"SC_SHRT_MAX", _SC_SHRT_MAX
},
7690 {"SC_SHRT_MIN", _SC_SHRT_MIN
},
7692 #ifdef _SC_SIGQUEUE_MAX
7693 {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX
},
7695 #ifdef _SC_SIGRT_MAX
7696 {"SC_SIGRT_MAX", _SC_SIGRT_MAX
},
7698 #ifdef _SC_SIGRT_MIN
7699 {"SC_SIGRT_MIN", _SC_SIGRT_MIN
},
7701 #ifdef _SC_SOFTPOWER
7702 {"SC_SOFTPOWER", _SC_SOFTPOWER
},
7704 #ifdef _SC_SPLIT_CACHE
7705 {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE
},
7707 #ifdef _SC_SSIZE_MAX
7708 {"SC_SSIZE_MAX", _SC_SSIZE_MAX
},
7710 #ifdef _SC_STACK_PROT
7711 {"SC_STACK_PROT", _SC_STACK_PROT
},
7713 #ifdef _SC_STREAM_MAX
7714 {"SC_STREAM_MAX", _SC_STREAM_MAX
},
7716 #ifdef _SC_SYNCHRONIZED_IO
7717 {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO
},
7720 {"SC_THREADS", _SC_THREADS
},
7722 #ifdef _SC_THREAD_ATTR_STACKADDR
7723 {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR
},
7725 #ifdef _SC_THREAD_ATTR_STACKSIZE
7726 {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE
},
7728 #ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
7729 {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS
},
7731 #ifdef _SC_THREAD_KEYS_MAX
7732 {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX
},
7734 #ifdef _SC_THREAD_PRIORITY_SCHEDULING
7735 {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING
},
7737 #ifdef _SC_THREAD_PRIO_INHERIT
7738 {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT
},
7740 #ifdef _SC_THREAD_PRIO_PROTECT
7741 {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT
},
7743 #ifdef _SC_THREAD_PROCESS_SHARED
7744 {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED
},
7746 #ifdef _SC_THREAD_SAFE_FUNCTIONS
7747 {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS
},
7749 #ifdef _SC_THREAD_STACK_MIN
7750 {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN
},
7752 #ifdef _SC_THREAD_THREADS_MAX
7753 {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX
},
7756 {"SC_TIMERS", _SC_TIMERS
},
7758 #ifdef _SC_TIMER_MAX
7759 {"SC_TIMER_MAX", _SC_TIMER_MAX
},
7761 #ifdef _SC_TTY_NAME_MAX
7762 {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX
},
7764 #ifdef _SC_TZNAME_MAX
7765 {"SC_TZNAME_MAX", _SC_TZNAME_MAX
},
7767 #ifdef _SC_T_IOV_MAX
7768 {"SC_T_IOV_MAX", _SC_T_IOV_MAX
},
7770 #ifdef _SC_UCHAR_MAX
7771 {"SC_UCHAR_MAX", _SC_UCHAR_MAX
},
7774 {"SC_UINT_MAX", _SC_UINT_MAX
},
7776 #ifdef _SC_UIO_MAXIOV
7777 {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV
},
7779 #ifdef _SC_ULONG_MAX
7780 {"SC_ULONG_MAX", _SC_ULONG_MAX
},
7782 #ifdef _SC_USHRT_MAX
7783 {"SC_USHRT_MAX", _SC_USHRT_MAX
},
7786 {"SC_VERSION", _SC_VERSION
},
7789 {"SC_WORD_BIT", _SC_WORD_BIT
},
7791 #ifdef _SC_XBS5_ILP32_OFF32
7792 {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32
},
7794 #ifdef _SC_XBS5_ILP32_OFFBIG
7795 {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG
},
7797 #ifdef _SC_XBS5_LP64_OFF64
7798 {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64
},
7800 #ifdef _SC_XBS5_LPBIG_OFFBIG
7801 {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG
},
7803 #ifdef _SC_XOPEN_CRYPT
7804 {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT
},
7806 #ifdef _SC_XOPEN_ENH_I18N
7807 {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N
},
7809 #ifdef _SC_XOPEN_LEGACY
7810 {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY
},
7812 #ifdef _SC_XOPEN_REALTIME
7813 {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME
},
7815 #ifdef _SC_XOPEN_REALTIME_THREADS
7816 {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS
},
7818 #ifdef _SC_XOPEN_SHM
7819 {"SC_XOPEN_SHM", _SC_XOPEN_SHM
},
7821 #ifdef _SC_XOPEN_UNIX
7822 {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX
},
7824 #ifdef _SC_XOPEN_VERSION
7825 {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION
},
7827 #ifdef _SC_XOPEN_XCU_VERSION
7828 {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION
},
7830 #ifdef _SC_XOPEN_XPG2
7831 {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2
},
7833 #ifdef _SC_XOPEN_XPG3
7834 {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3
},
7836 #ifdef _SC_XOPEN_XPG4
7837 {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4
},
7842 conv_sysconf_confname(PyObject
*arg
, int *valuep
)
7844 return conv_confname(arg
, valuep
, posix_constants_sysconf
,
7845 sizeof(posix_constants_sysconf
)
7846 / sizeof(struct constdef
));
7849 PyDoc_STRVAR(posix_sysconf__doc__
,
7850 "sysconf(name) -> integer\n\n\
7851 Return an integer-valued system configuration variable.");
7854 posix_sysconf(PyObject
*self
, PyObject
*args
)
7856 PyObject
*result
= NULL
;
7859 if (PyArg_ParseTuple(args
, "O&:sysconf", conv_sysconf_confname
, &name
)) {
7863 value
= sysconf(name
);
7864 if (value
== -1 && errno
!= 0)
7867 result
= PyInt_FromLong(value
);
7874 /* This code is used to ensure that the tables of configuration value names
7875 * are in sorted order as required by conv_confname(), and also to build the
7876 * the exported dictionaries that are used to publish information about the
7877 * names available on the host platform.
7879 * Sorting the table at runtime ensures that the table is properly ordered
7880 * when used, even for platforms we're not able to test on. It also makes
7881 * it easier to add additional entries to the tables.
7885 cmp_constdefs(const void *v1
, const void *v2
)
7887 const struct constdef
*c1
=
7888 (const struct constdef
*) v1
;
7889 const struct constdef
*c2
=
7890 (const struct constdef
*) v2
;
7892 return strcmp(c1
->name
, c2
->name
);
7896 setup_confname_table(struct constdef
*table
, size_t tablesize
,
7897 char *tablename
, PyObject
*module
)
7902 qsort(table
, tablesize
, sizeof(struct constdef
), cmp_constdefs
);
7907 for (i
=0; i
< tablesize
; ++i
) {
7908 PyObject
*o
= PyInt_FromLong(table
[i
].value
);
7909 if (o
== NULL
|| PyDict_SetItemString(d
, table
[i
].name
, o
) == -1) {
7916 return PyModule_AddObject(module
, tablename
, d
);
7919 /* Return -1 on failure, 0 on success. */
7921 setup_confname_tables(PyObject
*module
)
7923 #if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
7924 if (setup_confname_table(posix_constants_pathconf
,
7925 sizeof(posix_constants_pathconf
)
7926 / sizeof(struct constdef
),
7927 "pathconf_names", module
))
7931 if (setup_confname_table(posix_constants_confstr
,
7932 sizeof(posix_constants_confstr
)
7933 / sizeof(struct constdef
),
7934 "confstr_names", module
))
7938 if (setup_confname_table(posix_constants_sysconf
,
7939 sizeof(posix_constants_sysconf
)
7940 / sizeof(struct constdef
),
7941 "sysconf_names", module
))
7948 PyDoc_STRVAR(posix_abort__doc__
,
7949 "abort() -> does not return!\n\n\
7950 Abort the interpreter immediately. This 'dumps core' or otherwise fails\n\
7951 in the hardest way possible on the hosting operating system.");
7954 posix_abort(PyObject
*self
, PyObject
*noargs
)
7958 Py_FatalError("abort() called from Python code didn't abort!");
7963 PyDoc_STRVAR(win32_startfile__doc__
,
7964 "startfile(filepath [, operation]) - Start a file with its associated\n\
7967 When \"operation\" is not specified or \"open\", this acts like\n\
7968 double-clicking the file in Explorer, or giving the file name as an\n\
7969 argument to the DOS \"start\" command: the file is opened with whatever\n\
7970 application (if any) its extension is associated.\n\
7971 When another \"operation\" is given, it specifies what should be done with\n\
7972 the file. A typical operation is \"print\".\n\
7974 startfile returns as soon as the associated application is launched.\n\
7975 There is no option to wait for the application to close, and no way\n\
7976 to retrieve the application's exit status.\n\
7978 The filepath is relative to the current directory. If you want to use\n\
7979 an absolute path, make sure the first character is not a slash (\"/\");\n\
7980 the underlying Win32 ShellExecute function doesn't work if it is.");
7983 win32_startfile(PyObject
*self
, PyObject
*args
)
7986 char *operation
= NULL
;
7988 #ifdef Py_WIN_WIDE_FILENAMES
7989 if (unicode_file_names()) {
7990 PyObject
*unipath
, *woperation
= NULL
;
7991 if (!PyArg_ParseTuple(args
, "U|s:startfile",
7992 &unipath
, &operation
)) {
7999 woperation
= PyUnicode_DecodeASCII(operation
,
8000 strlen(operation
), NULL
);
8008 Py_BEGIN_ALLOW_THREADS
8009 rc
= ShellExecuteW((HWND
)0, woperation
? PyUnicode_AS_UNICODE(woperation
) : 0,
8010 PyUnicode_AS_UNICODE(unipath
),
8011 NULL
, NULL
, SW_SHOWNORMAL
);
8012 Py_END_ALLOW_THREADS
8014 Py_XDECREF(woperation
);
8015 if (rc
<= (HINSTANCE
)32) {
8016 PyObject
*errval
= win32_error_unicode("startfile",
8017 PyUnicode_AS_UNICODE(unipath
));
8026 if (!PyArg_ParseTuple(args
, "et|s:startfile",
8027 Py_FileSystemDefaultEncoding
, &filepath
,
8030 Py_BEGIN_ALLOW_THREADS
8031 rc
= ShellExecute((HWND
)0, operation
, filepath
,
8032 NULL
, NULL
, SW_SHOWNORMAL
);
8033 Py_END_ALLOW_THREADS
8034 if (rc
<= (HINSTANCE
)32) {
8035 PyObject
*errval
= win32_error("startfile", filepath
);
8036 PyMem_Free(filepath
);
8039 PyMem_Free(filepath
);
8045 #ifdef HAVE_GETLOADAVG
8046 PyDoc_STRVAR(posix_getloadavg__doc__
,
8047 "getloadavg() -> (float, float, float)\n\n\
8048 Return the number of processes in the system run queue averaged over\n\
8049 the last 1, 5, and 15 minutes or raises OSError if the load average\n\
8053 posix_getloadavg(PyObject
*self
, PyObject
*noargs
)
8056 if (getloadavg(loadavg
, 3)!=3) {
8057 PyErr_SetString(PyExc_OSError
, "Load averages are unobtainable");
8060 return Py_BuildValue("ddd", loadavg
[0], loadavg
[1], loadavg
[2]);
8066 PyDoc_STRVAR(win32_urandom__doc__
,
8067 "urandom(n) -> str\n\n\
8068 Return a string of n random bytes suitable for cryptographic use.");
8070 typedef BOOL (WINAPI
*CRYPTACQUIRECONTEXTA
)(HCRYPTPROV
*phProv
,\
8071 LPCSTR pszContainer
, LPCSTR pszProvider
, DWORD dwProvType
,\
8073 typedef BOOL (WINAPI
*CRYPTGENRANDOM
)(HCRYPTPROV hProv
, DWORD dwLen
,\
8076 static CRYPTGENRANDOM pCryptGenRandom
= NULL
;
8077 static HCRYPTPROV hCryptProv
= 0;
8080 win32_urandom(PyObject
*self
, PyObject
*args
)
8085 /* Read arguments */
8086 if (! PyArg_ParseTuple(args
, "i:urandom", &howMany
))
8089 return PyErr_Format(PyExc_ValueError
,
8090 "negative argument not allowed");
8092 if (hCryptProv
== 0) {
8093 HINSTANCE hAdvAPI32
= NULL
;
8094 CRYPTACQUIRECONTEXTA pCryptAcquireContext
= NULL
;
8096 /* Obtain handle to the DLL containing CryptoAPI
8097 This should not fail */
8098 hAdvAPI32
= GetModuleHandle("advapi32.dll");
8099 if(hAdvAPI32
== NULL
)
8100 return win32_error("GetModuleHandle", NULL
);
8102 /* Obtain pointers to the CryptoAPI functions
8103 This will fail on some early versions of Win95 */
8104 pCryptAcquireContext
= (CRYPTACQUIRECONTEXTA
)GetProcAddress(
8106 "CryptAcquireContextA");
8107 if (pCryptAcquireContext
== NULL
)
8108 return PyErr_Format(PyExc_NotImplementedError
,
8109 "CryptAcquireContextA not found");
8111 pCryptGenRandom
= (CRYPTGENRANDOM
)GetProcAddress(
8112 hAdvAPI32
, "CryptGenRandom");
8113 if (pCryptGenRandom
== NULL
)
8114 return PyErr_Format(PyExc_NotImplementedError
,
8115 "CryptGenRandom not found");
8117 /* Acquire context */
8118 if (! pCryptAcquireContext(&hCryptProv
, NULL
, NULL
,
8119 PROV_RSA_FULL
, CRYPT_VERIFYCONTEXT
))
8120 return win32_error("CryptAcquireContext", NULL
);
8123 /* Allocate bytes */
8124 result
= PyString_FromStringAndSize(NULL
, howMany
);
8125 if (result
!= NULL
) {
8126 /* Get random data */
8127 if (! pCryptGenRandom(hCryptProv
, howMany
, (unsigned char*)
8128 PyString_AS_STRING(result
))) {
8130 return win32_error("CryptGenRandom", NULL
);
8138 /* Use openssl random routine */
8139 #include <openssl/rand.h>
8140 PyDoc_STRVAR(vms_urandom__doc__
,
8141 "urandom(n) -> str\n\n\
8142 Return a string of n random bytes suitable for cryptographic use.");
8145 vms_urandom(PyObject
*self
, PyObject
*args
)
8150 /* Read arguments */
8151 if (! PyArg_ParseTuple(args
, "i:urandom", &howMany
))
8154 return PyErr_Format(PyExc_ValueError
,
8155 "negative argument not allowed");
8157 /* Allocate bytes */
8158 result
= PyString_FromStringAndSize(NULL
, howMany
);
8159 if (result
!= NULL
) {
8160 /* Get random data */
8161 if (RAND_pseudo_bytes((unsigned char*)
8162 PyString_AS_STRING(result
),
8165 return PyErr_Format(PyExc_ValueError
,
8166 "RAND_pseudo_bytes");
8173 static PyMethodDef posix_methods
[] = {
8174 {"access", posix_access
, METH_VARARGS
, posix_access__doc__
},
8176 {"ttyname", posix_ttyname
, METH_VARARGS
, posix_ttyname__doc__
},
8178 {"chdir", posix_chdir
, METH_VARARGS
, posix_chdir__doc__
},
8180 {"chflags", posix_chflags
, METH_VARARGS
, posix_chflags__doc__
},
8181 #endif /* HAVE_CHFLAGS */
8182 {"chmod", posix_chmod
, METH_VARARGS
, posix_chmod__doc__
},
8184 {"chown", posix_chown
, METH_VARARGS
, posix_chown__doc__
},
8185 #endif /* HAVE_CHOWN */
8186 #ifdef HAVE_LCHFLAGS
8187 {"lchflags", posix_lchflags
, METH_VARARGS
, posix_lchflags__doc__
},
8188 #endif /* HAVE_LCHFLAGS */
8190 {"lchown", posix_lchown
, METH_VARARGS
, posix_lchown__doc__
},
8191 #endif /* HAVE_LCHOWN */
8193 {"chroot", posix_chroot
, METH_VARARGS
, posix_chroot__doc__
},
8196 {"ctermid", posix_ctermid
, METH_NOARGS
, posix_ctermid__doc__
},
8199 {"getcwd", posix_getcwd
, METH_NOARGS
, posix_getcwd__doc__
},
8200 #ifdef Py_USING_UNICODE
8201 {"getcwdu", posix_getcwdu
, METH_NOARGS
, posix_getcwdu__doc__
},
8205 {"link", posix_link
, METH_VARARGS
, posix_link__doc__
},
8206 #endif /* HAVE_LINK */
8207 {"listdir", posix_listdir
, METH_VARARGS
, posix_listdir__doc__
},
8208 {"lstat", posix_lstat
, METH_VARARGS
, posix_lstat__doc__
},
8209 {"mkdir", posix_mkdir
, METH_VARARGS
, posix_mkdir__doc__
},
8211 {"nice", posix_nice
, METH_VARARGS
, posix_nice__doc__
},
8212 #endif /* HAVE_NICE */
8213 #ifdef HAVE_READLINK
8214 {"readlink", posix_readlink
, METH_VARARGS
, posix_readlink__doc__
},
8215 #endif /* HAVE_READLINK */
8216 {"rename", posix_rename
, METH_VARARGS
, posix_rename__doc__
},
8217 {"rmdir", posix_rmdir
, METH_VARARGS
, posix_rmdir__doc__
},
8218 {"stat", posix_stat
, METH_VARARGS
, posix_stat__doc__
},
8219 {"stat_float_times", stat_float_times
, METH_VARARGS
, stat_float_times__doc__
},
8221 {"symlink", posix_symlink
, METH_VARARGS
, posix_symlink__doc__
},
8222 #endif /* HAVE_SYMLINK */
8224 {"system", posix_system
, METH_VARARGS
, posix_system__doc__
},
8226 {"umask", posix_umask
, METH_VARARGS
, posix_umask__doc__
},
8228 {"uname", posix_uname
, METH_NOARGS
, posix_uname__doc__
},
8229 #endif /* HAVE_UNAME */
8230 {"unlink", posix_unlink
, METH_VARARGS
, posix_unlink__doc__
},
8231 {"remove", posix_unlink
, METH_VARARGS
, posix_remove__doc__
},
8232 {"utime", posix_utime
, METH_VARARGS
, posix_utime__doc__
},
8234 {"times", posix_times
, METH_NOARGS
, posix_times__doc__
},
8235 #endif /* HAVE_TIMES */
8236 {"_exit", posix__exit
, METH_VARARGS
, posix__exit__doc__
},
8238 {"execv", posix_execv
, METH_VARARGS
, posix_execv__doc__
},
8239 {"execve", posix_execve
, METH_VARARGS
, posix_execve__doc__
},
8240 #endif /* HAVE_EXECV */
8242 {"spawnv", posix_spawnv
, METH_VARARGS
, posix_spawnv__doc__
},
8243 {"spawnve", posix_spawnve
, METH_VARARGS
, posix_spawnve__doc__
},
8244 #if defined(PYOS_OS2)
8245 {"spawnvp", posix_spawnvp
, METH_VARARGS
, posix_spawnvp__doc__
},
8246 {"spawnvpe", posix_spawnvpe
, METH_VARARGS
, posix_spawnvpe__doc__
},
8247 #endif /* PYOS_OS2 */
8248 #endif /* HAVE_SPAWNV */
8250 {"fork1", posix_fork1
, METH_NOARGS
, posix_fork1__doc__
},
8251 #endif /* HAVE_FORK1 */
8253 {"fork", posix_fork
, METH_NOARGS
, posix_fork__doc__
},
8254 #endif /* HAVE_FORK */
8255 #if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
8256 {"openpty", posix_openpty
, METH_NOARGS
, posix_openpty__doc__
},
8257 #endif /* HAVE_OPENPTY || HAVE__GETPTY || HAVE_DEV_PTMX */
8259 {"forkpty", posix_forkpty
, METH_NOARGS
, posix_forkpty__doc__
},
8260 #endif /* HAVE_FORKPTY */
8262 {"getegid", posix_getegid
, METH_NOARGS
, posix_getegid__doc__
},
8263 #endif /* HAVE_GETEGID */
8265 {"geteuid", posix_geteuid
, METH_NOARGS
, posix_geteuid__doc__
},
8266 #endif /* HAVE_GETEUID */
8268 {"getgid", posix_getgid
, METH_NOARGS
, posix_getgid__doc__
},
8269 #endif /* HAVE_GETGID */
8270 #ifdef HAVE_GETGROUPS
8271 {"getgroups", posix_getgroups
, METH_NOARGS
, posix_getgroups__doc__
},
8273 {"getpid", posix_getpid
, METH_NOARGS
, posix_getpid__doc__
},
8275 {"getpgrp", posix_getpgrp
, METH_NOARGS
, posix_getpgrp__doc__
},
8276 #endif /* HAVE_GETPGRP */
8278 {"getppid", posix_getppid
, METH_NOARGS
, posix_getppid__doc__
},
8279 #endif /* HAVE_GETPPID */
8281 {"getuid", posix_getuid
, METH_NOARGS
, posix_getuid__doc__
},
8282 #endif /* HAVE_GETUID */
8283 #ifdef HAVE_GETLOGIN
8284 {"getlogin", posix_getlogin
, METH_NOARGS
, posix_getlogin__doc__
},
8287 {"kill", posix_kill
, METH_VARARGS
, posix_kill__doc__
},
8288 #endif /* HAVE_KILL */
8290 {"killpg", posix_killpg
, METH_VARARGS
, posix_killpg__doc__
},
8291 #endif /* HAVE_KILLPG */
8293 {"plock", posix_plock
, METH_VARARGS
, posix_plock__doc__
},
8294 #endif /* HAVE_PLOCK */
8296 {"popen", posix_popen
, METH_VARARGS
, posix_popen__doc__
},
8298 {"popen2", win32_popen2
, METH_VARARGS
},
8299 {"popen3", win32_popen3
, METH_VARARGS
},
8300 {"popen4", win32_popen4
, METH_VARARGS
},
8301 {"startfile", win32_startfile
, METH_VARARGS
, win32_startfile__doc__
},
8303 #if defined(PYOS_OS2) && defined(PYCC_GCC)
8304 {"popen2", os2emx_popen2
, METH_VARARGS
},
8305 {"popen3", os2emx_popen3
, METH_VARARGS
},
8306 {"popen4", os2emx_popen4
, METH_VARARGS
},
8309 #endif /* HAVE_POPEN */
8311 {"setuid", posix_setuid
, METH_VARARGS
, posix_setuid__doc__
},
8312 #endif /* HAVE_SETUID */
8314 {"seteuid", posix_seteuid
, METH_VARARGS
, posix_seteuid__doc__
},
8315 #endif /* HAVE_SETEUID */
8317 {"setegid", posix_setegid
, METH_VARARGS
, posix_setegid__doc__
},
8318 #endif /* HAVE_SETEGID */
8319 #ifdef HAVE_SETREUID
8320 {"setreuid", posix_setreuid
, METH_VARARGS
, posix_setreuid__doc__
},
8321 #endif /* HAVE_SETREUID */
8322 #ifdef HAVE_SETREGID
8323 {"setregid", posix_setregid
, METH_VARARGS
, posix_setregid__doc__
},
8324 #endif /* HAVE_SETREGID */
8326 {"setgid", posix_setgid
, METH_VARARGS
, posix_setgid__doc__
},
8327 #endif /* HAVE_SETGID */
8328 #ifdef HAVE_SETGROUPS
8329 {"setgroups", posix_setgroups
, METH_O
, posix_setgroups__doc__
},
8330 #endif /* HAVE_SETGROUPS */
8332 {"getpgid", posix_getpgid
, METH_VARARGS
, posix_getpgid__doc__
},
8333 #endif /* HAVE_GETPGID */
8335 {"setpgrp", posix_setpgrp
, METH_NOARGS
, posix_setpgrp__doc__
},
8336 #endif /* HAVE_SETPGRP */
8338 {"wait", posix_wait
, METH_NOARGS
, posix_wait__doc__
},
8339 #endif /* HAVE_WAIT */
8341 {"wait3", posix_wait3
, METH_VARARGS
, posix_wait3__doc__
},
8342 #endif /* HAVE_WAIT3 */
8344 {"wait4", posix_wait4
, METH_VARARGS
, posix_wait4__doc__
},
8345 #endif /* HAVE_WAIT4 */
8346 #if defined(HAVE_WAITPID) || defined(HAVE_CWAIT)
8347 {"waitpid", posix_waitpid
, METH_VARARGS
, posix_waitpid__doc__
},
8348 #endif /* HAVE_WAITPID */
8350 {"getsid", posix_getsid
, METH_VARARGS
, posix_getsid__doc__
},
8351 #endif /* HAVE_GETSID */
8353 {"setsid", posix_setsid
, METH_NOARGS
, posix_setsid__doc__
},
8354 #endif /* HAVE_SETSID */
8356 {"setpgid", posix_setpgid
, METH_VARARGS
, posix_setpgid__doc__
},
8357 #endif /* HAVE_SETPGID */
8358 #ifdef HAVE_TCGETPGRP
8359 {"tcgetpgrp", posix_tcgetpgrp
, METH_VARARGS
, posix_tcgetpgrp__doc__
},
8360 #endif /* HAVE_TCGETPGRP */
8361 #ifdef HAVE_TCSETPGRP
8362 {"tcsetpgrp", posix_tcsetpgrp
, METH_VARARGS
, posix_tcsetpgrp__doc__
},
8363 #endif /* HAVE_TCSETPGRP */
8364 {"open", posix_open
, METH_VARARGS
, posix_open__doc__
},
8365 {"close", posix_close
, METH_VARARGS
, posix_close__doc__
},
8366 {"dup", posix_dup
, METH_VARARGS
, posix_dup__doc__
},
8367 {"dup2", posix_dup2
, METH_VARARGS
, posix_dup2__doc__
},
8368 {"lseek", posix_lseek
, METH_VARARGS
, posix_lseek__doc__
},
8369 {"read", posix_read
, METH_VARARGS
, posix_read__doc__
},
8370 {"write", posix_write
, METH_VARARGS
, posix_write__doc__
},
8371 {"fstat", posix_fstat
, METH_VARARGS
, posix_fstat__doc__
},
8372 {"fdopen", posix_fdopen
, METH_VARARGS
, posix_fdopen__doc__
},
8373 {"isatty", posix_isatty
, METH_VARARGS
, posix_isatty__doc__
},
8375 {"pipe", posix_pipe
, METH_NOARGS
, posix_pipe__doc__
},
8378 {"mkfifo", posix_mkfifo
, METH_VARARGS
, posix_mkfifo__doc__
},
8380 #if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
8381 {"mknod", posix_mknod
, METH_VARARGS
, posix_mknod__doc__
},
8383 #ifdef HAVE_DEVICE_MACROS
8384 {"major", posix_major
, METH_VARARGS
, posix_major__doc__
},
8385 {"minor", posix_minor
, METH_VARARGS
, posix_minor__doc__
},
8386 {"makedev", posix_makedev
, METH_VARARGS
, posix_makedev__doc__
},
8388 #ifdef HAVE_FTRUNCATE
8389 {"ftruncate", posix_ftruncate
, METH_VARARGS
, posix_ftruncate__doc__
},
8392 {"putenv", posix_putenv
, METH_VARARGS
, posix_putenv__doc__
},
8394 #ifdef HAVE_UNSETENV
8395 {"unsetenv", posix_unsetenv
, METH_VARARGS
, posix_unsetenv__doc__
},
8397 #ifdef HAVE_STRERROR
8398 {"strerror", posix_strerror
, METH_VARARGS
, posix_strerror__doc__
},
8401 {"fchdir", posix_fchdir
, METH_O
, posix_fchdir__doc__
},
8404 {"fsync", posix_fsync
, METH_O
, posix_fsync__doc__
},
8406 #ifdef HAVE_FDATASYNC
8407 {"fdatasync", posix_fdatasync
, METH_O
, posix_fdatasync__doc__
},
8409 #ifdef HAVE_SYS_WAIT_H
8411 {"WCOREDUMP", posix_WCOREDUMP
, METH_VARARGS
, posix_WCOREDUMP__doc__
},
8412 #endif /* WCOREDUMP */
8414 {"WIFCONTINUED",posix_WIFCONTINUED
, METH_VARARGS
, posix_WIFCONTINUED__doc__
},
8415 #endif /* WIFCONTINUED */
8417 {"WIFSTOPPED", posix_WIFSTOPPED
, METH_VARARGS
, posix_WIFSTOPPED__doc__
},
8418 #endif /* WIFSTOPPED */
8420 {"WIFSIGNALED", posix_WIFSIGNALED
, METH_VARARGS
, posix_WIFSIGNALED__doc__
},
8421 #endif /* WIFSIGNALED */
8423 {"WIFEXITED", posix_WIFEXITED
, METH_VARARGS
, posix_WIFEXITED__doc__
},
8424 #endif /* WIFEXITED */
8426 {"WEXITSTATUS", posix_WEXITSTATUS
, METH_VARARGS
, posix_WEXITSTATUS__doc__
},
8427 #endif /* WEXITSTATUS */
8429 {"WTERMSIG", posix_WTERMSIG
, METH_VARARGS
, posix_WTERMSIG__doc__
},
8430 #endif /* WTERMSIG */
8432 {"WSTOPSIG", posix_WSTOPSIG
, METH_VARARGS
, posix_WSTOPSIG__doc__
},
8433 #endif /* WSTOPSIG */
8434 #endif /* HAVE_SYS_WAIT_H */
8435 #if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
8436 {"fstatvfs", posix_fstatvfs
, METH_VARARGS
, posix_fstatvfs__doc__
},
8438 #if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
8439 {"statvfs", posix_statvfs
, METH_VARARGS
, posix_statvfs__doc__
},
8442 {"tmpfile", posix_tmpfile
, METH_NOARGS
, posix_tmpfile__doc__
},
8445 {"tempnam", posix_tempnam
, METH_VARARGS
, posix_tempnam__doc__
},
8448 {"tmpnam", posix_tmpnam
, METH_NOARGS
, posix_tmpnam__doc__
},
8451 {"confstr", posix_confstr
, METH_VARARGS
, posix_confstr__doc__
},
8454 {"sysconf", posix_sysconf
, METH_VARARGS
, posix_sysconf__doc__
},
8456 #ifdef HAVE_FPATHCONF
8457 {"fpathconf", posix_fpathconf
, METH_VARARGS
, posix_fpathconf__doc__
},
8459 #ifdef HAVE_PATHCONF
8460 {"pathconf", posix_pathconf
, METH_VARARGS
, posix_pathconf__doc__
},
8462 {"abort", posix_abort
, METH_NOARGS
, posix_abort__doc__
},
8464 {"_getfullpathname", posix__getfullpathname
, METH_VARARGS
, NULL
},
8466 #ifdef HAVE_GETLOADAVG
8467 {"getloadavg", posix_getloadavg
, METH_NOARGS
, posix_getloadavg__doc__
},
8470 {"urandom", win32_urandom
, METH_VARARGS
, win32_urandom__doc__
},
8473 {"urandom", vms_urandom
, METH_VARARGS
, vms_urandom__doc__
},
8475 {NULL
, NULL
} /* Sentinel */
8480 ins(PyObject
*module
, char *symbol
, long value
)
8482 return PyModule_AddIntConstant(module
, symbol
, value
);
8485 #if defined(PYOS_OS2)
8486 /* Insert Platform-Specific Constant Values (Strings & Numbers) of Common Use */
8487 static int insertvalues(PyObject
*module
)
8490 ULONG values
[QSV_MAX
+1];
8494 Py_BEGIN_ALLOW_THREADS
8495 rc
= DosQuerySysInfo(1L, QSV_MAX
, &values
[1], sizeof(ULONG
) * QSV_MAX
);
8496 Py_END_ALLOW_THREADS
8498 if (rc
!= NO_ERROR
) {
8503 if (ins(module
, "meminstalled", values
[QSV_TOTPHYSMEM
])) return -1;
8504 if (ins(module
, "memkernel", values
[QSV_TOTRESMEM
])) return -1;
8505 if (ins(module
, "memvirtual", values
[QSV_TOTAVAILMEM
])) return -1;
8506 if (ins(module
, "maxpathlen", values
[QSV_MAX_PATH_LENGTH
])) return -1;
8507 if (ins(module
, "maxnamelen", values
[QSV_MAX_COMP_LENGTH
])) return -1;
8508 if (ins(module
, "revision", values
[QSV_VERSION_REVISION
])) return -1;
8509 if (ins(module
, "timeslice", values
[QSV_MIN_SLICE
])) return -1;
8511 switch (values
[QSV_VERSION_MINOR
]) {
8512 case 0: ver
= "2.00"; break;
8513 case 10: ver
= "2.10"; break;
8514 case 11: ver
= "2.11"; break;
8515 case 30: ver
= "3.00"; break;
8516 case 40: ver
= "4.00"; break;
8517 case 50: ver
= "5.00"; break;
8519 PyOS_snprintf(tmp
, sizeof(tmp
),
8520 "%d-%d", values
[QSV_VERSION_MAJOR
],
8521 values
[QSV_VERSION_MINOR
]);
8525 /* Add Indicator of the Version of the Operating System */
8526 if (PyModule_AddStringConstant(module
, "version", tmp
) < 0)
8529 /* Add Indicator of Which Drive was Used to Boot the System */
8530 tmp
[0] = 'A' + values
[QSV_BOOT_DRIVE
] - 1;
8534 return PyModule_AddStringConstant(module
, "bootdrive", tmp
);
8539 all_ins(PyObject
*d
)
8542 if (ins(d
, "F_OK", (long)F_OK
)) return -1;
8545 if (ins(d
, "R_OK", (long)R_OK
)) return -1;
8548 if (ins(d
, "W_OK", (long)W_OK
)) return -1;
8551 if (ins(d
, "X_OK", (long)X_OK
)) return -1;
8554 if (ins(d
, "NGROUPS_MAX", (long)NGROUPS_MAX
)) return -1;
8557 if (ins(d
, "TMP_MAX", (long)TMP_MAX
)) return -1;
8560 if (ins(d
, "WCONTINUED", (long)WCONTINUED
)) return -1;
8563 if (ins(d
, "WNOHANG", (long)WNOHANG
)) return -1;
8566 if (ins(d
, "WUNTRACED", (long)WUNTRACED
)) return -1;
8569 if (ins(d
, "O_RDONLY", (long)O_RDONLY
)) return -1;
8572 if (ins(d
, "O_WRONLY", (long)O_WRONLY
)) return -1;
8575 if (ins(d
, "O_RDWR", (long)O_RDWR
)) return -1;
8578 if (ins(d
, "O_NDELAY", (long)O_NDELAY
)) return -1;
8581 if (ins(d
, "O_NONBLOCK", (long)O_NONBLOCK
)) return -1;
8584 if (ins(d
, "O_APPEND", (long)O_APPEND
)) return -1;
8587 if (ins(d
, "O_DSYNC", (long)O_DSYNC
)) return -1;
8590 if (ins(d
, "O_RSYNC", (long)O_RSYNC
)) return -1;
8593 if (ins(d
, "O_SYNC", (long)O_SYNC
)) return -1;
8596 if (ins(d
, "O_NOCTTY", (long)O_NOCTTY
)) return -1;
8599 if (ins(d
, "O_CREAT", (long)O_CREAT
)) return -1;
8602 if (ins(d
, "O_EXCL", (long)O_EXCL
)) return -1;
8605 if (ins(d
, "O_TRUNC", (long)O_TRUNC
)) return -1;
8608 if (ins(d
, "O_BINARY", (long)O_BINARY
)) return -1;
8611 if (ins(d
, "O_TEXT", (long)O_TEXT
)) return -1;
8614 if (ins(d
, "O_LARGEFILE", (long)O_LARGEFILE
)) return -1;
8617 if (ins(d
, "O_SHLOCK", (long)O_SHLOCK
)) return -1;
8620 if (ins(d
, "O_EXLOCK", (long)O_EXLOCK
)) return -1;
8625 /* Don't inherit in child processes. */
8626 if (ins(d
, "O_NOINHERIT", (long)O_NOINHERIT
)) return -1;
8628 #ifdef _O_SHORT_LIVED
8629 /* Optimize for short life (keep in memory). */
8630 /* MS forgot to define this one with a non-underscore form too. */
8631 if (ins(d
, "O_SHORT_LIVED", (long)_O_SHORT_LIVED
)) return -1;
8634 /* Automatically delete when last handle is closed. */
8635 if (ins(d
, "O_TEMPORARY", (long)O_TEMPORARY
)) return -1;
8638 /* Optimize for random access. */
8639 if (ins(d
, "O_RANDOM", (long)O_RANDOM
)) return -1;
8642 /* Optimize for sequential access. */
8643 if (ins(d
, "O_SEQUENTIAL", (long)O_SEQUENTIAL
)) return -1;
8646 /* GNU extensions. */
8648 /* Direct disk access. */
8649 if (ins(d
, "O_DIRECT", (long)O_DIRECT
)) return -1;
8652 /* Must be a directory. */
8653 if (ins(d
, "O_DIRECTORY", (long)O_DIRECTORY
)) return -1;
8656 /* Do not follow links. */
8657 if (ins(d
, "O_NOFOLLOW", (long)O_NOFOLLOW
)) return -1;
8660 /* These come from sysexits.h */
8662 if (ins(d
, "EX_OK", (long)EX_OK
)) return -1;
8665 if (ins(d
, "EX_USAGE", (long)EX_USAGE
)) return -1;
8666 #endif /* EX_USAGE */
8668 if (ins(d
, "EX_DATAERR", (long)EX_DATAERR
)) return -1;
8669 #endif /* EX_DATAERR */
8671 if (ins(d
, "EX_NOINPUT", (long)EX_NOINPUT
)) return -1;
8672 #endif /* EX_NOINPUT */
8674 if (ins(d
, "EX_NOUSER", (long)EX_NOUSER
)) return -1;
8675 #endif /* EX_NOUSER */
8677 if (ins(d
, "EX_NOHOST", (long)EX_NOHOST
)) return -1;
8678 #endif /* EX_NOHOST */
8679 #ifdef EX_UNAVAILABLE
8680 if (ins(d
, "EX_UNAVAILABLE", (long)EX_UNAVAILABLE
)) return -1;
8681 #endif /* EX_UNAVAILABLE */
8683 if (ins(d
, "EX_SOFTWARE", (long)EX_SOFTWARE
)) return -1;
8684 #endif /* EX_SOFTWARE */
8686 if (ins(d
, "EX_OSERR", (long)EX_OSERR
)) return -1;
8687 #endif /* EX_OSERR */
8689 if (ins(d
, "EX_OSFILE", (long)EX_OSFILE
)) return -1;
8690 #endif /* EX_OSFILE */
8692 if (ins(d
, "EX_CANTCREAT", (long)EX_CANTCREAT
)) return -1;
8693 #endif /* EX_CANTCREAT */
8695 if (ins(d
, "EX_IOERR", (long)EX_IOERR
)) return -1;
8696 #endif /* EX_IOERR */
8698 if (ins(d
, "EX_TEMPFAIL", (long)EX_TEMPFAIL
)) return -1;
8699 #endif /* EX_TEMPFAIL */
8701 if (ins(d
, "EX_PROTOCOL", (long)EX_PROTOCOL
)) return -1;
8702 #endif /* EX_PROTOCOL */
8704 if (ins(d
, "EX_NOPERM", (long)EX_NOPERM
)) return -1;
8705 #endif /* EX_NOPERM */
8707 if (ins(d
, "EX_CONFIG", (long)EX_CONFIG
)) return -1;
8708 #endif /* EX_CONFIG */
8710 if (ins(d
, "EX_NOTFOUND", (long)EX_NOTFOUND
)) return -1;
8711 #endif /* EX_NOTFOUND */
8714 #if defined(PYOS_OS2) && defined(PYCC_GCC)
8715 if (ins(d
, "P_WAIT", (long)P_WAIT
)) return -1;
8716 if (ins(d
, "P_NOWAIT", (long)P_NOWAIT
)) return -1;
8717 if (ins(d
, "P_OVERLAY", (long)P_OVERLAY
)) return -1;
8718 if (ins(d
, "P_DEBUG", (long)P_DEBUG
)) return -1;
8719 if (ins(d
, "P_SESSION", (long)P_SESSION
)) return -1;
8720 if (ins(d
, "P_DETACH", (long)P_DETACH
)) return -1;
8721 if (ins(d
, "P_PM", (long)P_PM
)) return -1;
8722 if (ins(d
, "P_DEFAULT", (long)P_DEFAULT
)) return -1;
8723 if (ins(d
, "P_MINIMIZE", (long)P_MINIMIZE
)) return -1;
8724 if (ins(d
, "P_MAXIMIZE", (long)P_MAXIMIZE
)) return -1;
8725 if (ins(d
, "P_FULLSCREEN", (long)P_FULLSCREEN
)) return -1;
8726 if (ins(d
, "P_WINDOWED", (long)P_WINDOWED
)) return -1;
8727 if (ins(d
, "P_FOREGROUND", (long)P_FOREGROUND
)) return -1;
8728 if (ins(d
, "P_BACKGROUND", (long)P_BACKGROUND
)) return -1;
8729 if (ins(d
, "P_NOCLOSE", (long)P_NOCLOSE
)) return -1;
8730 if (ins(d
, "P_NOSESSION", (long)P_NOSESSION
)) return -1;
8731 if (ins(d
, "P_QUOTE", (long)P_QUOTE
)) return -1;
8732 if (ins(d
, "P_TILDE", (long)P_TILDE
)) return -1;
8733 if (ins(d
, "P_UNRELATED", (long)P_UNRELATED
)) return -1;
8734 if (ins(d
, "P_DEBUGDESC", (long)P_DEBUGDESC
)) return -1;
8736 if (ins(d
, "P_WAIT", (long)_P_WAIT
)) return -1;
8737 if (ins(d
, "P_NOWAIT", (long)_P_NOWAIT
)) return -1;
8738 if (ins(d
, "P_OVERLAY", (long)_OLD_P_OVERLAY
)) return -1;
8739 if (ins(d
, "P_NOWAITO", (long)_P_NOWAITO
)) return -1;
8740 if (ins(d
, "P_DETACH", (long)_P_DETACH
)) return -1;
8744 #if defined(PYOS_OS2)
8745 if (insertvalues(d
)) return -1;
8751 #if (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__BORLANDC__)) && !defined(__QNX__)
8752 #define INITFUNC initnt
8753 #define MODNAME "nt"
8755 #elif defined(PYOS_OS2)
8756 #define INITFUNC initos2
8757 #define MODNAME "os2"
8760 #define INITFUNC initposix
8761 #define MODNAME "posix"
8769 m
= Py_InitModule3(MODNAME
,
8775 /* Initialize environ dictionary */
8776 v
= convertenviron();
8778 if (v
== NULL
|| PyModule_AddObject(m
, "environ", v
) != 0)
8785 if (setup_confname_tables(m
))
8788 Py_INCREF(PyExc_OSError
);
8789 PyModule_AddObject(m
, "error", PyExc_OSError
);
8792 if (posix_putenv_garbage
== NULL
)
8793 posix_putenv_garbage
= PyDict_New();
8797 stat_result_desc
.name
= MODNAME
".stat_result";
8798 stat_result_desc
.fields
[7].name
= PyStructSequence_UnnamedField
;
8799 stat_result_desc
.fields
[8].name
= PyStructSequence_UnnamedField
;
8800 stat_result_desc
.fields
[9].name
= PyStructSequence_UnnamedField
;
8801 PyStructSequence_InitType(&StatResultType
, &stat_result_desc
);
8802 structseq_new
= StatResultType
.tp_new
;
8803 StatResultType
.tp_new
= statresult_new
;
8805 statvfs_result_desc
.name
= MODNAME
".statvfs_result";
8806 PyStructSequence_InitType(&StatVFSResultType
, &statvfs_result_desc
);
8808 Py_INCREF((PyObject
*) &StatResultType
);
8809 PyModule_AddObject(m
, "stat_result", (PyObject
*) &StatResultType
);
8810 Py_INCREF((PyObject
*) &StatVFSResultType
);
8811 PyModule_AddObject(m
, "statvfs_result",
8812 (PyObject
*) &StatVFSResultType
);
8817 * Step 2 of weak-linking support on Mac OS X.
8819 * The code below removes functions that are not available on the
8820 * currently active platform.
8822 * This block allow one to use a python binary that was build on
8823 * OSX 10.4 on OSX 10.3, without loosing access to new APIs on
8826 #ifdef HAVE_FSTATVFS
8827 if (fstatvfs
== NULL
) {
8828 if (PyObject_DelAttrString(m
, "fstatvfs") == -1) {
8832 #endif /* HAVE_FSTATVFS */
8835 if (statvfs
== NULL
) {
8836 if (PyObject_DelAttrString(m
, "statvfs") == -1) {
8840 #endif /* HAVE_STATVFS */
8843 if (lchown
== NULL
) {
8844 if (PyObject_DelAttrString(m
, "lchown") == -1) {
8848 #endif /* HAVE_LCHOWN */
8851 #endif /* __APPLE__ */