Understanding and using sql server sys.dm_exec_requests
Содержание:
Executing Interactive Programs
LV: One place where developers may be surprised is trying to execute an external program that they expect will interact with the user. For instance:
$ cat io.p
#include <stdio.h>
int main()
{
char val1, val2;
printf("please enter first number: ");
gets(val1);
printf("please enter second number: ");
gets(val2);
printf("thank you\n");
exit(0);
}
If the developer would compile this program (which, granted, does nothing useful), they might be surprised to find that coding
exec gcc io.c -o io exec ./io
does not result in the display of the prompts. The reason for this is that Tcl’s exec has created a pipe for stdout, since the general case of using exec is more likely a construct like
set results [exec ./io]
and that the program would run to completion, after which exec would take the output and assign it to the variable.
So, one has to code around the default behavior if a more interactive access is needed. Over on comp.lang.tcl, Alexandre Ferrieux wrote, in the thread ‘Problem in calling c programs and compiling them in tcl/tk from mid November, 2008, that one needs to use something like:
exec ./io >@ stdout 2>@ stderr
(adding the catch construct around it and possibly the -ignorestderr depending on the behavior of the program).
Spaces in Path of Executable
When there is whitespace in the path of the exectable, e.g.,
set executable c:\Program Files\Tcl\bin\wish.exe
The following will work:
exec $executable
However, when exec is paired with eval, the executable would then become two separate words. Here’s one way to keep it together:
eval exec
MG: Another solution is to force the shortname, without spaces:
set path {c:\Program Files\Tcl\bin\wish.exe}
catch {set path }
On Windows, $path will now be set to
C:/PROGRA~1/Tcl/bin/wish.exe
you can add in a file nativename if you want to keep back slashes instead of forward slashes. In fact, it’s probably a good idea to do that whenever you’re passing a path to something outside your own program, if you can’t guarantee that it, and anything it may need to call, can handle paths with spaces. The only time you really need to use the real path is when you’re displaying it to the user for something, at which point something clearer to read is preferable.
NOTES top
The default search path (used when the environment does not contain
the variable PATH) shows some variation across systems. It generally
includes /bin and /usr/bin (in that order) and may also include the
current working directory. On some other systems, the current
working is included after /bin and /usr/bin, as an anti-Trojan-horse
measure. The glibc implementation long followed the traditional
default where the current working directory is included at the start
of the search path. However, some code refactoring during the
development of glibc 2.24 caused the current working directory to be
dropped altogether from the default search path. This accidental
behavior change is considered mildly beneficial, and won't be
reverted.
The behavior of execlp() and execvp() when errors occur while
attempting to execute the file is historic practice, but has not
traditionally been documented and is not specified by the POSIX
standard. BSD (and possibly other systems) do an automatic sleep and
retry if ETXTBSY is encountered. Linux treats it as a hard error and
returns immediately.
Traditionally, the functions execlp() and execvp() ignored all errors
except for the ones described above and ENOMEM and E2BIG, upon which
they returned. They now return if any error other than the ones
described above occurs.
Executing string
To execute a string, construct the string and pass it to the EXEC SQL command. Please refer to the below example which executes a string.
| 1 | EXEC(‘select LocationID,LocationName from locations’) |
Following is the example of using EXEC with string constructed from a variable. You always need to enclose the string in the brackets else execute statement consider it as a stored procedure and throws an error as shown in the below image.
Constructing a string from the variable and executing it using EXEC SQL command may inject unwanted code. There are some techniques to avoid SQL injection. We will review those techniques in another article.
|
1 |
declare@sqlvarchar(max),@iint set@i=3 SET@sql=’select LocationID,LocationName from locations where LocationID = ‘+cast(@iasvarchar(10)) EXEC(@SQL) |
PORTING ISSUES
The NuTCRACKER Platform uses the Win32 CreateProcess() function to
create the new process image, and does not overlay the existing image,
as is done on most UNIX systems.
This is visible only in that the process ID returned by
getpid() in the new process image does not match
that returned in the calling process image.
Refer to Process Management in the
Windows Concepts chapter of the
PTC MKS Toolkit UNIX to Windows Porting Guide.
You may not call an exec() function from a non-NuTCRACKER Platform
application (for example, from a standalone NuTCRACKER Platform DLL used in a native Win32
application), except from the child of a vfork()
operation.
Refer to Building Standalone DLLs in the
Porting Shared Libraries chapter of the
PTC MKS Toolkit UNIX to Windows Porting Guide
for more information.
The Windows file systems do not support set-user-ID and set-group-ID bits
for files. Hence there is no support for automatically setting effective
user and/or group IDs at process execution time.
If the process being executed is not a NuTCRACKER Platform process, only the standard file
descriptors (0, 1, 2 — stdin, stdout,
stderr) are available to the new process.
However, if that process then invokes a NuTCRACKER Platform process, all inherited file
descriptors are available to the grandchild NuTCRACKER Platform process.
You must ensure that any path name arguments you pass to non-NuTCRACKER Platform
applications are in Win32 format, as only NuTCRACKER Platform applications
recognize the NuTCRACKER Platform format.
Refer to Path Names
in the Windows Concepts chapter of the
PTC MKS Toolkit UNIX to Windows Porting Guide
for more information.
Priorities are inherited by new threads in the same way as on UNIX systems.
Even the first thread created by a native Win32 process inherits priority
in this manner. However, further creation of threads not under control of
the NuTCRACKER Platform might revert to THREAD_PRIORITY_NORMAL.
Executable paths are treated as multibyte sequences and are converted to Unicode (UTF-16)
before passing to Win32. The conversion is either performed based on the
current thread locale, set using uselocale() or the process locale
as set by a call to setlocale(), and overridden by _NutConf()
_NC_SET_ANSI_LOCALE and _NC_SET_UTF8_LOCALE options. Under all other
conditions, the multibyte sequences are considered to be from the ANSI code page for the current windows system locale.
Environment variables are sonsidered to be multibyte sequences and converted to Unicode (UTF-16)
only when _NutConf() is called to set _NC_SET_UTF8_LOCALE.
Environment variables are converted from OEM in the Windows system locale to Unicode (UTF-16)
only when _NutConf()
is called to set _NC_SET_OEM_ENVIRONMENT. Otherwise environment variables are
considered to be ANSI strings in the current system locale.
The argument arrays are sonsidered to be multibyte sequences and converted to Unicode (UTF-16)
only when _NutConf() is called to set _NC_SET_UTF8_LOCALE.
Otherwise argument arrays are considered to be ANSI strings in the current system locale.
Description
Let us see the description of the terms used in above EXEC statement syntax.
POSITIONAL-PARAM
These are positional parameters, which can be of two types:
| Positional Parameter | Description |
|---|---|
| PGM | This refers to the program name to be executed in the job step. |
| PROC | This refers to the procedure name to be executed in the job step. We will discuss it a separate chapter. |
KEYWORD-PARAM
Following are the various keyword parameters for EXEC statement. You can use one or more parameters based on requirements and they are separated by comma:
| Keyword Parameter | Description |
|---|---|
| PARM |
Used to provide parametrized data to the program that is being executed in the job step. This is a program dependant field and do not have definite rules, except that the PARM value has to be included within quotation in the event of having special characters. For example given below, the value «CUST1000» is passed as an alphanumeric value to the program. If the program is in COBOL, the value passed through a PARM parameter in a JCL is received in the LINKAGE SECTION of the program. |
| ADDRSPC |
This is used to specify whether the job step require virtual or real storage for execution. Virtual storage is pageable whereas real storage is not and is placed in the main memory for execution. Job steps, which require faster execution can be placed in real storage. Following is the syntax: ADDRSPC=VIRT | REAL When an ADDRSPC is not coded, VIRT is the default one. |
| ACCT |
This specifies the accounting information of the job step. Following is the syntax: ACCT=(userid) This is similar to the positional parameter accounting information in the JOB statement. If it is coded both in JOB and EXEC statement, then the accounting information in JOB statement applies to all job steps where an ACCT parameter is not coded. The ACCT parameter in an EXEC statement will override the one present in the JOB statement for that job step only. |
Errors
- E2BIG
The total number of bytes in the environment (envp) and argument list (argv) is too large.
EACCES
Search permission is denied on a component of the path prefix of filename or the name of a script interpreter. (See also path_resolution(7).)
EACCES
The file or a script interpreter is not a regular file.
EACCES
Execute permission is denied for the file or a script or ELF interpreter.
EACCES
The file system is mounted noexec.
EFAULT
filename points outside your accessible address space.
EINVAL
An ELF executable had more than one PT_INTERP segment (i.e., tried to name more than one interpreter).
EIO
An I/O error occurred.
EISDIR
An ELF interpreter was a directory.
ELIBBAD
An ELF interpreter was not in a recognized format.
ELOOP
Too many symbolic links were encountered in resolving filename or the name of a script or ELF interpreter.
EMFILE
The process has the maximum number of files open.
ENAMETOOLONG
filename is too long.
ENFILE
The system limit on the total number of open files has been reached.
ENOENT
The file filename or a script or ELF interpreter does not exist, or a shared library needed for file or interpreter cannot be found.
ENOEXEC
An executable is not in a recognized format, is for the wrong architecture, or has some other format error that means it cannot be executed.
ENOMEM
Insufficient kernel memory was available.
ENOTDIR
A component of the path prefix of filename or a script or ELF interpreter is not a directory.
EPERM
The file system is mounted nosuid, the user is not the superuser, and the file has the set-user-ID or set-group-ID bit set.
EPERM
The process is being traced, the user is not the superuser and the file has the set-user-ID or set-group-ID bit set.
ETXTBSY
Executable was open for writing by one or more processes.
Common Keyword Parameters of EXEC and JOB Statement
| Keyword Parameter | Description |
|---|---|
| ADDRSPC | ADDRSPC coded in JOB statement overrides the ADDRSPC coded in EXEC statement of any job step. |
| TIME | If TIME is coded in an EXEC statement, then it applies to that job step only. If it is specified in both JOB and EXEC statement, then both will be in effect and can cause time-out error due to either of it. It is not recommended to use TIME parameter in both the JOB and EXEC statement together. |
| REGION |
If REGION is coded in an EXEC statement, then it applies to that job step only. REGION coded in JOB statement overrides the REGION coded in EXEC statement of any job step. |
| COND |
Used to control the job step execution based on the return-code of the previous step. If a COND parameter is coded in an EXEC statement of a job step, then the COND parameter of the JOB statement (if present) is ignored. The various tests that can be performed using a COND parameter is explained in conditional Processing. |
Executing queries on a remote server
AT linked_server_name clause along with EXEC command is used to execute queries on a remote server. A linked server must be configured and RPC Out option must be enabled on the linked server to execute queries on a remote server.
Please refer to the following example of executing a query on a remote server. Replace the linked server name with your linked server name.
| 1 | EXEC(‘select name,database_id,db_name() as CurrentDB from sys.databases where database_id <=4’)atTEST01V |
If we do not specify the database name, EXEC SQL statement will execute the query on the default database of the login used in the linked server.
If you want to execute query in a specific database use “USE databasename” in the query. Please refer to the below example.
|
1 |
EXEC(‘use msdb; select name,database_id,db_name() as CurrentDB from sys.databases where database_id <=4’)atTEST01V |
We can also issue a select query against the remote server using four-part notation. We must enable the Data Access option on the linked server. Please refer to the below example.
|
1 |
selectname,database_idfromTEST01V.master.sys.databaseswheredatabase_id<=4 |
To execute a stored procedure on a remote server, use below T-SQL script by replacing the linked server name, database name, and the stored procedure name.
| 1 | EXEC(‘use testdb; EXEC TestProcedure’)atTEST01V |
Following is the example of executing a stored procedure on the linked server using four-part notation. Here “TEST01V” is the server name, “test” is the database name, and “dbo” is the schema name.
| 1 | EXECTEST01V.test.dbo.testProc |
COLOPHON top
This page is part of release 5.08 of the Linux man-pages project. A
description of the project, information about reporting bugs, and the
latest version of this page, can be found at
https://www.kernel.org/doc/man-pages/.
Linux 2020-08-13 EXECVE(2)
Pages that refer to this page:
pmcd(1),
setpriv(1),
strace(1),
access(2),
alarm(2),
arch_prctl(2),
brk(2),
chdir(2),
chmod(2),
chroot(2),
clone2(2),
__clone2(2),
clone(2),
clone3(2),
close(2),
creat(2),
eventfd2(2),
eventfd(2),
execveat(2),
exit(2),
_exit(2),
_Exit(2),
faccessat(2),
fanotify_mark(2),
fchdir(2),
fchmod(2),
fchmodat(2),
fcntl(2),
fcntl64(2),
flock(2),
fork(2),
getgroups(2),
getgroups32(2),
getitimer(2),
getpgid(2),
getpgrp(2),
getpriority(2),
getrlimit(2),
get_robust_list(2),
getrusage(2),
ioctl(2),
ioctl_console(2),
ioperm(2),
iopl(2),
keyctl(2),
madvise(2),
memfd_create(2),
mlock2(2),
mlock(2),
mlockall(2),
mount(2),
munlock(2),
munlockall(2),
open(2),
openat(2),
perf_event_open(2),
prctl(2),
prlimit(2),
prlimit64(2),
ptrace(2),
rt_sigaction(2),
rt_sigpending(2),
rt_sigprocmask(2),
sbrk(2),
sched_getaffinity(2),
sched_setaffinity(2),
seccomp(2),
semop(2),
semtimedop(2),
setgroups(2),
setgroups32(2),
setitimer(2),
set_mempolicy(2),
setpgid(2),
setpgrp(2),
setpriority(2),
setregid(2),
setregid32(2),
setresgid(2),
setresgid32(2),
setresuid(2),
setresuid32(2),
setreuid(2),
setreuid32(2),
setrlimit(2),
set_robust_list(2),
setsid(2),
setuid(2),
setuid32(2),
shmat(2),
shmdt(2),
shmop(2),
sigaction(2),
sigaltstack(2),
signalfd(2),
signalfd4(2),
sigpending(2),
sigprocmask(2),
syscalls(2),
timer_create(2),
timerfd_create(2),
timerfd_gettime(2),
timerfd_settime(2),
ugetrlimit(2),
umask(2),
vfork(2),
cap_get_fd(3),
cap_get_file(3),
cap_set_fd(3),
cap_set_file(3),
catclose(3),
catopen(3),
eventfd_read(3),
eventfd_write(3),
exec(3),
execl(3),
execle(3),
execlp(3),
execv(3),
execvp(3),
execvpe(3),
exit(3),
fexecve(3),
getexeccon(3),
getexeccon_raw(3),
getfscreatecon(3),
getfscreatecon_raw(3),
getkeycreatecon(3),
getkeycreatecon_raw(3),
getsockcreatecon(3),
getsockcreatecon_raw(3),
libexpect(3),
mq_close(3),
posix_spawn(3),
posix_spawnp(3),
pthread_atfork(3),
pthread_kill_other_threads_np(3),
pthread_mutexattr_getrobust(3),
pthread_mutexattr_getrobust_np(3),
pthread_mutexattr_setrobust(3),
pthread_mutexattr_setrobust_np(3),
rpm_execcon(3),
sd_bus_creds_get_audit_login_uid(3),
sd_bus_creds_get_audit_session_id(3),
sd_bus_creds_get_cgroup(3),
sd_bus_creds_get_cmdline(3),
sd_bus_creds_get_comm(3),
sd_bus_creds_get_description(3),
sd_bus_creds_get_egid(3),
sd_bus_creds_get_euid(3),
sd_bus_creds_get_exe(3),
sd_bus_creds_get_fsgid(3),
sd_bus_creds_get_fsuid(3),
sd_bus_creds_get_gid(3),
sd_bus_creds_get_owner_uid(3),
sd_bus_creds_get_pid(3),
sd_bus_creds_get_ppid(3),
sd_bus_creds_get_selinux_context(3),
sd_bus_creds_get_session(3),
sd_bus_creds_get_sgid(3),
sd_bus_creds_get_slice(3),
sd_bus_creds_get_suid(3),
sd_bus_creds_get_supplementary_gids(3),
sd_bus_creds_get_tid(3),
sd_bus_creds_get_tid_comm(3),
sd_bus_creds_get_tty(3),
sd_bus_creds_get_uid(3),
sd_bus_creds_get_unique_name(3),
sd_bus_creds_get_unit(3),
sd_bus_creds_get_user_slice(3),
sd_bus_creds_get_user_unit(3),
sd_bus_creds_get_well_known_names(3),
sd_bus_creds_has_bounding_cap(3),
sd_bus_creds_has_effective_cap(3),
sd_bus_creds_has_inheritable_cap(3),
sd_bus_creds_has_permitted_cap(3),
sem_close(3),
setexeccon(3),
setexeccon_raw(3),
setfscreatecon(3),
setfscreatecon_raw(3),
setkeycreatecon(3),
setkeycreatecon_raw(3),
setsockcreatecon(3),
setsockcreatecon_raw(3),
sigblock(3),
siggetmask(3),
sigmask(3),
sigsetmask(3),
sigstack(3),
sigvec(3),
system(3),
vlimit(3),
vtimes(3),
console_ioctl(4),
core(5),
elf(5),
proc(5),
procfs(5),
system.conf.d(5),
systemd.exec(5),
systemd-system.conf(5),
systemd-user.conf(5),
user.conf.d(5),
capabilities(7),
cgroups(7),
credentials(7),
environ(7),
inode(7),
inotify(7),
persistent-keyring(7),
process-keyring(7),
pthreads(7),
sched(7),
session-keyring(7),
signal(7),
signal-safety(7),
thread-keyring(7),
user-keyring(7),
user_namespaces(7),
user-session-keyring(7),
vdso(7),
pam_selinux(8)
Executing a stored procedure
To execute a stored procedure using EXEC pass the procedure name and parameters if any. Please refer to the below T-SQL script to execute a stored procedure.
| 1 | EXECGetLocations@LocID=1 |
We can also assign the value returned by a stored procedure to a variable. Please refer to the following example T-SQL script.
|
1 |
IFEXISTS(SELECT1FROMSYS.procedureswherename=’GetLocations’) BEGIN DROPPROCEDUREGetLocations END CREATEPROCEDUREGetLocations (@LocIDint) AS declare@iint selectLocationID,LocationNamefromLocationswhereLocationID=@LocID SET@I=2 RETURN@I DECLARE@retunr_statusint EXEC@retunr_status=GetLocations@LocID=1 SELECT@retunr_statusASReturnStatus |
Notes
Set-user-ID and set-group-ID processes can not be ptrace(2)d.
Linux ignores the set-user-ID and set-group-ID bits on scripts.
The result of mounting a file system nosuid varies across Linux kernel versions: some will refuse execution of set-user-ID and set-group-ID
executables when this would give the user powers she did not have already (and return EPERM), some will just ignore the set-user-ID and set-group-ID
bits and exec() successfully.
A maximum line length of 127 characters is allowed for the first line in a #! executable shell script.
The semantics of the optional-arg argument of an interpreter script vary across implementations. On Linux, the entire string following the
interpreter name is passed as a single argument to the interpreter, and this string can include white space. However, behavior differs on some other
systems. Some systems use the first white space to terminate optional-arg. On some systems, an interpreter script can have multiple arguments, and white
spaces in optional-arg are used to delimit the arguments.
On Linux, argv can be specified as NULL, which has the same effect as specifying this argument as a pointer to a list containing a single NULL
pointer. Do not take advantage of this misfeature! It is nonstandard and nonportable: on most other UNIX systems doing this will result in an error
(EFAULT).
POSIX.1-2001 says that values returned by sysconf(3) should be invariant over the lifetime of a process. However, since Linux 2.6.23, if the
RLIMIT_STACK resource limit changes, then the value reported by _SC_ARG_MAX will also change, to reflect the fact that the limit on space for
holding command-line arguments and environment variables has changed.
Historical
- With UNIX V6 the argument list of an exec() call was ended by 0, while the argument list of main was ended by -1. Thus, this argument list was
not directly usable in a further exec() call. Since UNIX V7 both are NULL.
exec and Starkits
Guillaume Plenier 2005-07-28: I am currently working at a starpack including executables for which I wrote a Tk graphical interface. Everything works fine on my computer because the executable files are in my path, but if I take the starpack and run it under another computer, I have error messages like » -executable- command not find» or something close to that. I tried several things to indicate where my executable files are for exec to find them, but apparently exec looks in the computer path variable to find the unknown programs and not where indicated (I changed env(PATH), used $starkit::topdir etc…)
MG 2005-07-28: You could try something like this:
set paths [list ~/path/number/1 ~/path/number/2 ../path/number/3]
set success 0
foreach x $paths {
if {]} {
set success 1
exec
break;
}
}
if {! $success} {
# we didn't find it in any of out paths - try just exec'ing and hope for the best
catch {exec $fileToExec}
}
Peter Newman 2005-07-29: DOS/Windows can’t run EXEs (or DLLs) that are physically in the StarKit/Pack. You’ll have to extract them first. MHo: Concerning DLLs, you are wrong: Doing a load in Starkits/Starpacks automatically copies the DLLs to a temporary location before loading…. execx could be a partial solution for exec…
For more info. check out the freewrap docs. There’s discussion there about embedded binary files — and some techniques for dealing with them.
Guillaume Plenier 2005-07-31: I don’t like the idea of extracting my executables first and will probably try to find other solutions.
Using a Windows .bat File
AM 2004-03-17: I ran into a strange phenomenon while trying to tame an external program on Windows:
- I used open |myprog.exe to start the program (as usual, in combination with fileevent)
- Rather than a nice display of the output of this program in a window, I saw a mass of DOS boxes appear and disappear. Presumably the program I tried to control was calling out to batch files or other programs …
- I could solve this (with help from the Tkchat room) by executing the program via an ordinary batch file. This was the incantation:
set infile ]
It can probably be stripped down, but this worked fantastically (the batch file, run.bat simply starts the original program and that is now quietly doing its job).
Типы файлов LCK
Ассоциация основного файла LCK
.LCK
| Формат файла: | .lck |
| Тип файла: | Program Lock File |
Расширение LCK Файл обычно связан с файлом управления доступом, который используется для блокировки файлов базы данных, которые в настоящее время используются от просмотра или изменены другими пользователями. Файл LCK обычно открыт с файлом, который не используется и заблокирован, когда пользователь работает на файл, и это позволяет избежать случайной перезаписи изменений и любые возможные повреждения данных.
| Создатель: | Autodesk, Inc. |
| Категория файла: | Необычные файлы |
| Ключ реестра: | HKEY_CLASSES_ROOT\.lck |
Программные обеспечения, открывающие Program Lock File:
Adobe Dreamweaver, разработчик — Adobe Systems Incorporated
Совместимый с:
| Windows |
| Mac |
Autodesk Inventor, разработчик — Autodesk, Inc.
Совместимый с:
| Windows |
Adobe PageMaker, разработчик — Adobe Systems Incorporated
Совместимый с:
| Windows |
| Mac |
Устранение неполадок при открытии файлов LCK
Общие проблемы с открытием файлов LCK
Adobe Dreamweaver не установлен
Дважды щелкнув по файлу LCK вы можете увидеть системное диалоговое окно, в котором сообщается «Не удается открыть этот тип файла». В этом случае обычно это связано с тем, что на вашем компьютере не установлено Adobe Dreamweaver для %%os%%. Так как ваша операционная система не знает, что делать с этим файлом, вы не сможете открыть его дважды щелкнув на него.
Совет: Если вам извстна другая программа, которая может открыть файл LCK, вы можете попробовать открыть данный файл, выбрав это приложение из списка возможных программ.
Установлена неправильная версия Adobe Dreamweaver
В некоторых случаях у вас может быть более новая (или более старая) версия файла Program Lock File, не поддерживаемая установленной версией приложения. При отсутствии правильной версии ПО Adobe Dreamweaver (или любой из других программ, перечисленных выше), может потребоваться загрузить другую версию ПО или одного из других прикладных программных средств, перечисленных выше. Такая проблема чаще всего возникает при работе в более старой версии прикладного программного средства с файлом, созданным в более новой версии, который старая версия не может распознать.
Совет: Иногда вы можете получить общее представление о версии файла LCK, щелкнув правой кнопкой мыши на файл, а затем выбрав «Свойства» (Windows) или «Получить информацию» (Mac OSX).
Резюме: В любом случае, большинство проблем, возникающих во время открытия файлов LCK, связаны с отсутствием на вашем компьютере установленного правильного прикладного программного средства.
Даже если на вашем компьютере уже установлено Adobe Dreamweaver или другое программное обеспечение, связанное с LCK, вы все равно можете столкнуться с проблемами во время открытия файлов Program Lock File. Если проблемы открытия файлов LCK до сих пор не устранены, возможно, причина кроется в других проблемах, не позволяющих открыть эти файлы. Такие проблемы включают (представлены в порядке от наиболее до наименее распространенных):
PARAMETERS
- path
-
Specifies the path name of the new process image file.
- file
-
Is used to construct a path name that identifies the new process
image file. If it contains a slash character, the argument is used
as the path name for this file. Otherwise, the path prefix for this
file is obtained by a search of the directories in the environment variable
PATH. If PATH is not set, the current
directory is searched. - arg0, …, argn
-
Point to null-terminated character strings.
These strings constitute the argument list for the new process image.
The list is terminated by a NULL pointer.
The argument arg0 should point to a
file name that is associated with the process being
started by the exec() function. - argv
-
Is the argument list for the new process image.
This should contain an array of pointers to character strings,
and the array should be terminated by a NULL pointer.
The value in argv should point to a file name that is
associated with the process being started by the exec()
function. - envp
-
Specifies the environment for the new process image.
This should contain an array of pointers to character strings,
and the array should be terminated by a NULL pointer.
Перенаправление ввода/вывода
Практически все операционные системы обладают механизмом перенаправления ввода/вывода.
Linux не является исключением из этого правила. Обычно программы вводят текстовые данные с
консоли (терминала) и выводят данные на консоль. При вводе под консолью подразумевается клавиатура, а при выводе — дисплей терминала. Клавиатура и дисплей — это, соответственно, стандартный ввод и вывод (stdin и stdout). Любой ввод/вывод можно интерпретировать как ввод из некоторого файла и вывод в файл. Работа с файлами производится через их дескрипторы. Для организации ввода/вывода в UNIX используются три файла: stdin (дескриптор 1), stdout (2) и stderr(3).
Символ > используется для перенаправления стандартного вывода в файл.
Пример:
$ cat > newfile.txt
Стандартный ввод команды cat будет перенаправлен в файл newfile.txt, который будет создан после выполнения этой команды. Если файл с этим именем уже существует, то он будет перезаписан. Нажатие Ctrl + D остановит перенаправление и прерывает выполнение команды cat.
Символ < используется для переназначения стандартного ввода команды. Например, при выполнении команды cat Символ >> используется для присоединения данных в конец файла (append) стандартного вывода команды. Например, в отличие от случая с символом >, выполнение команды cat >> newfile.txt не перезапишет файл в случае его существования, а добавит данные в его конец.
Символ | используется для перенаправления стандартного вывода одной программы на стандартный ввод другой. Напрмер, ps -ax | grep httpd.