(procfs_system_process_attributes): Fix last change.
[bpt/emacs.git] / src / process.c
1 /* Asynchronous subprocess control for GNU Emacs.
2 Copyright (C) 1985, 1986, 1987, 1988, 1993, 1994, 1995,
3 1996, 1998, 1999, 2001, 2002, 2003, 2004,
4 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
5
6 This file is part of GNU Emacs.
7
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20
21
22 #include <config.h>
23 #include <signal.h>
24
25 /* This file is split into two parts by the following preprocessor
26 conditional. The 'then' clause contains all of the support for
27 asynchronous subprocesses. The 'else' clause contains stub
28 versions of some of the asynchronous subprocess routines that are
29 often called elsewhere in Emacs, so we don't have to #ifdef the
30 sections that call them. */
31
32 \f
33 #ifdef subprocesses
34
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <ctype.h>
38 #include <errno.h>
39 #include <setjmp.h>
40 #include <sys/types.h> /* some typedefs are used in sys/file.h */
41 #include <sys/file.h>
42 #include <sys/stat.h>
43 #ifdef HAVE_INTTYPES_H
44 #include <inttypes.h>
45 #endif
46
47 #ifdef HAVE_PWD_H
48 #include <pwd.h>
49 #include <grp.h>
50 #endif
51
52 #ifdef HAVE_UNISTD_H
53 #include <unistd.h>
54 #endif
55 #include <fcntl.h>
56
57 #ifdef HAVE_SOCKETS /* TCP connection support, if kernel can do it */
58 #include <sys/socket.h>
59 #include <netdb.h>
60 #include <netinet/in.h>
61 #include <arpa/inet.h>
62
63 /* Are local (unix) sockets supported? */
64 #if defined (HAVE_SYS_UN_H)
65 #if !defined (AF_LOCAL) && defined (AF_UNIX)
66 #define AF_LOCAL AF_UNIX
67 #endif
68 #ifdef AF_LOCAL
69 #define HAVE_LOCAL_SOCKETS
70 #include <sys/un.h>
71 #endif
72 #endif
73 #endif /* HAVE_SOCKETS */
74
75 #if defined(BSD_SYSTEM)
76 #include <sys/ioctl.h>
77 #if !defined (O_NDELAY) && defined (HAVE_PTYS) && !defined(USG5)
78 #include <fcntl.h>
79 #endif /* HAVE_PTYS and no O_NDELAY */
80 #endif /* BSD_SYSTEM */
81
82 #ifdef NEED_BSDTTY
83 #include <bsdtty.h>
84 #endif
85
86 /* Can we use SIOCGIFCONF and/or SIOCGIFADDR */
87 #ifdef HAVE_SOCKETS
88 #if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_NET_IF_H)
89 /* sys/ioctl.h may have been included already */
90 #ifndef SIOCGIFADDR
91 #include <sys/ioctl.h>
92 #endif
93 #include <net/if.h>
94 #endif
95 #endif
96
97 #ifdef HAVE_SYS_WAIT
98 #include <sys/wait.h>
99 #endif
100
101 #ifdef HAVE_RES_INIT
102 #include <netinet/in.h>
103 #include <arpa/nameser.h>
104 #include <resolv.h>
105 #endif
106
107 #include "lisp.h"
108 #include "systime.h"
109 #include "systty.h"
110
111 #include "window.h"
112 #include "buffer.h"
113 #include "character.h"
114 #include "coding.h"
115 #include "process.h"
116 #include "frame.h"
117 #include "termhooks.h"
118 #include "termopts.h"
119 #include "commands.h"
120 #include "keyboard.h"
121 #include "blockinput.h"
122 #include "dispextern.h"
123 #include "composite.h"
124 #include "atimer.h"
125
126 Lisp_Object Qprocessp;
127 Lisp_Object Qrun, Qstop, Qsignal;
128 Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
129 Lisp_Object Qlocal, Qipv4, Qdatagram;
130 Lisp_Object Qreal, Qnetwork, Qserial;
131 #ifdef AF_INET6
132 Lisp_Object Qipv6;
133 #endif
134 Lisp_Object QCport, QCspeed, QCprocess;
135 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
136 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
137 Lisp_Object QCname, QCbuffer, QChost, QCservice, QCtype;
138 Lisp_Object QClocal, QCremote, QCcoding;
139 Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
140 Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
141 Lisp_Object Qlast_nonmenu_event;
142 /* QCfamily is declared and initialized in xfaces.c,
143 QCfilter in keyboard.c. */
144 extern Lisp_Object QCfamily, QCfilter;
145
146 /* Qexit is declared and initialized in eval.c. */
147
148 /* QCfamily is defined in xfaces.c. */
149 extern Lisp_Object QCfamily;
150 /* QCfilter is defined in keyboard.c. */
151 extern Lisp_Object QCfilter;
152
153 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
154 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
155 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
156 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem;
157
158 #ifdef HAVE_SOCKETS
159 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
160 #define NETCONN1_P(p) (EQ ((p)->type, Qnetwork))
161 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
162 #define SERIALCONN1_P(p) (EQ ((p)->type, Qserial))
163 #else
164 #define NETCONN_P(p) 0
165 #define NETCONN1_P(p) 0
166 #define SERIALCONN_P(p) 0
167 #define SERIALCONN1_P(p) 0
168 #endif /* HAVE_SOCKETS */
169
170 /* Define first descriptor number available for subprocesses. */
171 #define FIRST_PROC_DESC 3
172
173 /* Define SIGCHLD as an alias for SIGCLD. There are many conditionals
174 testing SIGCHLD. */
175
176 #if !defined (SIGCHLD) && defined (SIGCLD)
177 #define SIGCHLD SIGCLD
178 #endif /* SIGCLD */
179
180 #include "syssignal.h"
181
182 #include "syswait.h"
183
184 extern char *get_operating_system_release ();
185
186 /* Serial processes require termios or Windows. */
187 #if defined (HAVE_TERMIOS) || defined (WINDOWSNT)
188 #define HAVE_SERIAL
189 #endif
190
191 #ifdef HAVE_SERIAL
192 /* From sysdep.c or w32.c */
193 extern int serial_open (char *port);
194 extern void serial_configure (struct Lisp_Process *p, Lisp_Object contact);
195 #endif
196
197 #ifndef USE_CRT_DLL
198 extern int errno;
199 #endif
200
201 #ifndef HAVE_H_ERRNO
202 extern int h_errno;
203 #endif
204
205 /* t means use pty, nil means use a pipe,
206 maybe other values to come. */
207 static Lisp_Object Vprocess_connection_type;
208
209 /* These next two vars are non-static since sysdep.c uses them in the
210 emulation of `select'. */
211 /* Number of events of change of status of a process. */
212 int process_tick;
213 /* Number of events for which the user or sentinel has been notified. */
214 int update_tick;
215
216 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
217
218 #ifdef BROKEN_NON_BLOCKING_CONNECT
219 #undef NON_BLOCKING_CONNECT
220 #else
221 #ifndef NON_BLOCKING_CONNECT
222 #ifdef HAVE_SOCKETS
223 #ifdef HAVE_SELECT
224 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
225 #if defined (O_NONBLOCK) || defined (O_NDELAY)
226 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
227 #define NON_BLOCKING_CONNECT
228 #endif /* EWOULDBLOCK || EINPROGRESS */
229 #endif /* O_NONBLOCK || O_NDELAY */
230 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
231 #endif /* HAVE_SELECT */
232 #endif /* HAVE_SOCKETS */
233 #endif /* NON_BLOCKING_CONNECT */
234 #endif /* BROKEN_NON_BLOCKING_CONNECT */
235
236 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
237 this system. We need to read full packets, so we need a
238 "non-destructive" select. So we require either native select,
239 or emulation of select using FIONREAD. */
240
241 #ifdef BROKEN_DATAGRAM_SOCKETS
242 #undef DATAGRAM_SOCKETS
243 #else
244 #ifndef DATAGRAM_SOCKETS
245 #ifdef HAVE_SOCKETS
246 #if defined (HAVE_SELECT) || defined (FIONREAD)
247 #if defined (HAVE_SENDTO) && defined (HAVE_RECVFROM) && defined (EMSGSIZE)
248 #define DATAGRAM_SOCKETS
249 #endif /* HAVE_SENDTO && HAVE_RECVFROM && EMSGSIZE */
250 #endif /* HAVE_SELECT || FIONREAD */
251 #endif /* HAVE_SOCKETS */
252 #endif /* DATAGRAM_SOCKETS */
253 #endif /* BROKEN_DATAGRAM_SOCKETS */
254
255 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
256 #ifdef EMACS_HAS_USECS
257 #define ADAPTIVE_READ_BUFFERING
258 #endif
259 #endif
260
261 #ifdef ADAPTIVE_READ_BUFFERING
262 #define READ_OUTPUT_DELAY_INCREMENT 10000
263 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
264 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
265
266 /* Number of processes which have a non-zero read_output_delay,
267 and therefore might be delayed for adaptive read buffering. */
268
269 static int process_output_delay_count;
270
271 /* Non-zero if any process has non-nil read_output_skip. */
272
273 static int process_output_skip;
274
275 /* Non-nil means to delay reading process output to improve buffering.
276 A value of t means that delay is reset after each send, any other
277 non-nil value does not reset the delay. A value of nil disables
278 adaptive read buffering completely. */
279 static Lisp_Object Vprocess_adaptive_read_buffering;
280 #else
281 #define process_output_delay_count 0
282 #endif
283
284
285 #include "sysselect.h"
286
287 static int keyboard_bit_set P_ ((SELECT_TYPE *));
288 static void deactivate_process P_ ((Lisp_Object));
289 static void status_notify P_ ((struct Lisp_Process *));
290 static int read_process_output P_ ((Lisp_Object, int));
291
292 /* If we support a window system, turn on the code to poll periodically
293 to detect C-g. It isn't actually used when doing interrupt input. */
294 #ifdef HAVE_WINDOW_SYSTEM
295 #define POLL_FOR_INPUT
296 #endif
297
298 static Lisp_Object get_process ();
299 static void exec_sentinel ();
300
301 extern EMACS_TIME timer_check ();
302 extern int timers_run;
303 \f
304 /* Mask of bits indicating the descriptors that we wait for input on. */
305
306 static SELECT_TYPE input_wait_mask;
307
308 /* Mask that excludes keyboard input descriptor(s). */
309
310 static SELECT_TYPE non_keyboard_wait_mask;
311
312 /* Mask that excludes process input descriptor(s). */
313
314 static SELECT_TYPE non_process_wait_mask;
315
316 /* Mask for the gpm mouse input descriptor. */
317
318 static SELECT_TYPE gpm_wait_mask;
319
320 #ifdef NON_BLOCKING_CONNECT
321 /* Mask of bits indicating the descriptors that we wait for connect to
322 complete on. Once they complete, they are removed from this mask
323 and added to the input_wait_mask and non_keyboard_wait_mask. */
324
325 static SELECT_TYPE connect_wait_mask;
326
327 /* Number of bits set in connect_wait_mask. */
328 static int num_pending_connects;
329
330 #define IF_NON_BLOCKING_CONNECT(s) s
331 #else
332 #define IF_NON_BLOCKING_CONNECT(s)
333 #endif
334
335 /* The largest descriptor currently in use for a process object. */
336 static int max_process_desc;
337
338 /* The largest descriptor currently in use for keyboard input. */
339 static int max_keyboard_desc;
340
341 /* The largest descriptor currently in use for gpm mouse input. */
342 static int max_gpm_desc;
343
344 /* Nonzero means delete a process right away if it exits. */
345 static int delete_exited_processes;
346
347 /* Indexed by descriptor, gives the process (if any) for that descriptor */
348 Lisp_Object chan_process[MAXDESC];
349
350 /* Alist of elements (NAME . PROCESS) */
351 Lisp_Object Vprocess_alist;
352
353 /* Buffered-ahead input char from process, indexed by channel.
354 -1 means empty (no char is buffered).
355 Used on sys V where the only way to tell if there is any
356 output from the process is to read at least one char.
357 Always -1 on systems that support FIONREAD. */
358
359 /* Don't make static; need to access externally. */
360 int proc_buffered_char[MAXDESC];
361
362 /* Table of `struct coding-system' for each process. */
363 static struct coding_system *proc_decode_coding_system[MAXDESC];
364 static struct coding_system *proc_encode_coding_system[MAXDESC];
365
366 #ifdef DATAGRAM_SOCKETS
367 /* Table of `partner address' for datagram sockets. */
368 struct sockaddr_and_len {
369 struct sockaddr *sa;
370 int len;
371 } datagram_address[MAXDESC];
372 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
373 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
374 #else
375 #define DATAGRAM_CHAN_P(chan) (0)
376 #define DATAGRAM_CONN_P(proc) (0)
377 #endif
378
379 /* Maximum number of bytes to send to a pty without an eof. */
380 static int pty_max_bytes;
381
382 /* Nonzero means don't run process sentinels. This is used
383 when exiting. */
384 int inhibit_sentinels;
385
386 #ifdef HAVE_PTYS
387 #ifdef HAVE_PTY_H
388 #include <pty.h>
389 #endif
390 /* The file name of the pty opened by allocate_pty. */
391
392 static char pty_name[24];
393 #endif
394 \f
395 /* Compute the Lisp form of the process status, p->status, from
396 the numeric status that was returned by `wait'. */
397
398 static Lisp_Object status_convert (int);
399
400 static void
401 update_status (p)
402 struct Lisp_Process *p;
403 {
404 eassert (p->raw_status_new);
405 p->status = status_convert (p->raw_status);
406 p->raw_status_new = 0;
407 }
408
409 /* Convert a process status word in Unix format to
410 the list that we use internally. */
411
412 static Lisp_Object
413 status_convert (int w)
414 {
415 if (WIFSTOPPED (w))
416 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
417 else if (WIFEXITED (w))
418 return Fcons (Qexit, Fcons (make_number (WRETCODE (w)),
419 WCOREDUMP (w) ? Qt : Qnil));
420 else if (WIFSIGNALED (w))
421 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
422 WCOREDUMP (w) ? Qt : Qnil));
423 else
424 return Qrun;
425 }
426
427 /* Given a status-list, extract the three pieces of information
428 and store them individually through the three pointers. */
429
430 static void
431 decode_status (l, symbol, code, coredump)
432 Lisp_Object l;
433 Lisp_Object *symbol;
434 int *code;
435 int *coredump;
436 {
437 Lisp_Object tem;
438
439 if (SYMBOLP (l))
440 {
441 *symbol = l;
442 *code = 0;
443 *coredump = 0;
444 }
445 else
446 {
447 *symbol = XCAR (l);
448 tem = XCDR (l);
449 *code = XFASTINT (XCAR (tem));
450 tem = XCDR (tem);
451 *coredump = !NILP (tem);
452 }
453 }
454
455 /* Return a string describing a process status list. */
456
457 static Lisp_Object
458 status_message (p)
459 struct Lisp_Process *p;
460 {
461 Lisp_Object status = p->status;
462 Lisp_Object symbol;
463 int code, coredump;
464 Lisp_Object string, string2;
465
466 decode_status (status, &symbol, &code, &coredump);
467
468 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
469 {
470 char *signame;
471 synchronize_system_messages_locale ();
472 signame = strsignal (code);
473 if (signame == 0)
474 signame = "unknown";
475 string = build_string (signame);
476 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
477 SSET (string, 0, DOWNCASE (SREF (string, 0)));
478 return concat2 (string, string2);
479 }
480 else if (EQ (symbol, Qexit))
481 {
482 if (NETCONN1_P (p))
483 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
484 if (code == 0)
485 return build_string ("finished\n");
486 string = Fnumber_to_string (make_number (code));
487 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
488 return concat3 (build_string ("exited abnormally with code "),
489 string, string2);
490 }
491 else if (EQ (symbol, Qfailed))
492 {
493 string = Fnumber_to_string (make_number (code));
494 string2 = build_string ("\n");
495 return concat3 (build_string ("failed with code "),
496 string, string2);
497 }
498 else
499 return Fcopy_sequence (Fsymbol_name (symbol));
500 }
501 \f
502 #ifdef HAVE_PTYS
503
504 /* Open an available pty, returning a file descriptor.
505 Return -1 on failure.
506 The file name of the terminal corresponding to the pty
507 is left in the variable pty_name. */
508
509 static int
510 allocate_pty ()
511 {
512 register int c, i;
513 int fd;
514
515 #ifdef PTY_ITERATION
516 PTY_ITERATION
517 #else
518 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
519 for (i = 0; i < 16; i++)
520 #endif
521 {
522 struct stat stb; /* Used in some PTY_OPEN. */
523 #ifdef PTY_NAME_SPRINTF
524 PTY_NAME_SPRINTF
525 #else
526 sprintf (pty_name, "/dev/pty%c%x", c, i);
527 #endif /* no PTY_NAME_SPRINTF */
528
529 #ifdef PTY_OPEN
530 PTY_OPEN;
531 #else /* no PTY_OPEN */
532 {
533 { /* Some systems name their pseudoterminals so that there are gaps in
534 the usual sequence - for example, on HP9000/S700 systems, there
535 are no pseudoterminals with names ending in 'f'. So we wait for
536 three failures in a row before deciding that we've reached the
537 end of the ptys. */
538 int failed_count = 0;
539
540 if (stat (pty_name, &stb) < 0)
541 {
542 failed_count++;
543 if (failed_count >= 3)
544 return -1;
545 }
546 else
547 failed_count = 0;
548 }
549 # ifdef O_NONBLOCK
550 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
551 # else
552 fd = emacs_open (pty_name, O_RDWR | O_NDELAY, 0);
553 # endif
554 }
555 #endif /* no PTY_OPEN */
556
557 if (fd >= 0)
558 {
559 /* check to make certain that both sides are available
560 this avoids a nasty yet stupid bug in rlogins */
561 #ifdef PTY_TTY_NAME_SPRINTF
562 PTY_TTY_NAME_SPRINTF
563 #else
564 sprintf (pty_name, "/dev/tty%c%x", c, i);
565 #endif /* no PTY_TTY_NAME_SPRINTF */
566 if (access (pty_name, 6) != 0)
567 {
568 emacs_close (fd);
569 # ifndef __sgi
570 continue;
571 # else
572 return -1;
573 # endif /* __sgi */
574 }
575 setup_pty (fd);
576 return fd;
577 }
578 }
579 return -1;
580 }
581 #endif /* HAVE_PTYS */
582 \f
583 static Lisp_Object
584 make_process (name)
585 Lisp_Object name;
586 {
587 register Lisp_Object val, tem, name1;
588 register struct Lisp_Process *p;
589 char suffix[10];
590 register int i;
591
592 p = allocate_process ();
593
594 p->infd = -1;
595 p->outfd = -1;
596 p->tick = 0;
597 p->update_tick = 0;
598 p->pid = 0;
599 p->pty_flag = 0;
600 p->raw_status_new = 0;
601 p->status = Qrun;
602 p->mark = Fmake_marker ();
603 p->kill_without_query = 0;
604
605 #ifdef ADAPTIVE_READ_BUFFERING
606 p->adaptive_read_buffering = 0;
607 p->read_output_delay = 0;
608 p->read_output_skip = 0;
609 #endif
610
611 /* If name is already in use, modify it until it is unused. */
612
613 name1 = name;
614 for (i = 1; ; i++)
615 {
616 tem = Fget_process (name1);
617 if (NILP (tem)) break;
618 sprintf (suffix, "<%d>", i);
619 name1 = concat2 (name, build_string (suffix));
620 }
621 name = name1;
622 p->name = name;
623 XSETPROCESS (val, p);
624 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
625 return val;
626 }
627
628 static void
629 remove_process (proc)
630 register Lisp_Object proc;
631 {
632 register Lisp_Object pair;
633
634 pair = Frassq (proc, Vprocess_alist);
635 Vprocess_alist = Fdelq (pair, Vprocess_alist);
636
637 deactivate_process (proc);
638 }
639
640 /* Setup coding systems of PROCESS. */
641
642 void
643 setup_process_coding_systems (process)
644 Lisp_Object process;
645 {
646 struct Lisp_Process *p = XPROCESS (process);
647 int inch = p->infd;
648 int outch = p->outfd;
649 Lisp_Object coding_system;
650
651 if (inch < 0 || outch < 0)
652 return;
653
654 if (!proc_decode_coding_system[inch])
655 proc_decode_coding_system[inch]
656 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
657 coding_system = p->decode_coding_system;
658 if (! NILP (p->filter))
659 ;
660 else if (BUFFERP (p->buffer))
661 {
662 if (NILP (XBUFFER (p->buffer)->enable_multibyte_characters))
663 coding_system = raw_text_coding_system (coding_system);
664 }
665 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
666
667 if (!proc_encode_coding_system[outch])
668 proc_encode_coding_system[outch]
669 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
670 setup_coding_system (p->encode_coding_system,
671 proc_encode_coding_system[outch]);
672 }
673 \f
674 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
675 doc: /* Return t if OBJECT is a process. */)
676 (object)
677 Lisp_Object object;
678 {
679 return PROCESSP (object) ? Qt : Qnil;
680 }
681
682 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
683 doc: /* Return the process named NAME, or nil if there is none. */)
684 (name)
685 register Lisp_Object name;
686 {
687 if (PROCESSP (name))
688 return name;
689 CHECK_STRING (name);
690 return Fcdr (Fassoc (name, Vprocess_alist));
691 }
692
693 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
694 doc: /* Return the (or a) process associated with BUFFER.
695 BUFFER may be a buffer or the name of one. */)
696 (buffer)
697 register Lisp_Object buffer;
698 {
699 register Lisp_Object buf, tail, proc;
700
701 if (NILP (buffer)) return Qnil;
702 buf = Fget_buffer (buffer);
703 if (NILP (buf)) return Qnil;
704
705 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
706 {
707 proc = Fcdr (XCAR (tail));
708 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
709 return proc;
710 }
711 return Qnil;
712 }
713
714 /* This is how commands for the user decode process arguments. It
715 accepts a process, a process name, a buffer, a buffer name, or nil.
716 Buffers denote the first process in the buffer, and nil denotes the
717 current buffer. */
718
719 static Lisp_Object
720 get_process (name)
721 register Lisp_Object name;
722 {
723 register Lisp_Object proc, obj;
724 if (STRINGP (name))
725 {
726 obj = Fget_process (name);
727 if (NILP (obj))
728 obj = Fget_buffer (name);
729 if (NILP (obj))
730 error ("Process %s does not exist", SDATA (name));
731 }
732 else if (NILP (name))
733 obj = Fcurrent_buffer ();
734 else
735 obj = name;
736
737 /* Now obj should be either a buffer object or a process object.
738 */
739 if (BUFFERP (obj))
740 {
741 proc = Fget_buffer_process (obj);
742 if (NILP (proc))
743 error ("Buffer %s has no process", SDATA (XBUFFER (obj)->name));
744 }
745 else
746 {
747 CHECK_PROCESS (obj);
748 proc = obj;
749 }
750 return proc;
751 }
752
753
754 #ifdef SIGCHLD
755 /* Fdelete_process promises to immediately forget about the process, but in
756 reality, Emacs needs to remember those processes until they have been
757 treated by sigchld_handler; otherwise this handler would consider the
758 process as being synchronous and say that the synchronous process is
759 dead. */
760 static Lisp_Object deleted_pid_list;
761 #endif
762
763 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
764 doc: /* Delete PROCESS: kill it and forget about it immediately.
765 PROCESS may be a process, a buffer, the name of a process or buffer, or
766 nil, indicating the current buffer's process. */)
767 (process)
768 register Lisp_Object process;
769 {
770 register struct Lisp_Process *p;
771
772 process = get_process (process);
773 p = XPROCESS (process);
774
775 p->raw_status_new = 0;
776 if (NETCONN1_P (p) || SERIALCONN1_P (p))
777 {
778 p->status = Fcons (Qexit, Fcons (make_number (0), Qnil));
779 p->tick = ++process_tick;
780 status_notify (p);
781 }
782 else if (p->infd >= 0)
783 {
784 #ifdef SIGCHLD
785 Lisp_Object symbol;
786 /* Assignment to EMACS_INT stops GCC whining about limited range
787 of data type. */
788 EMACS_INT pid = p->pid;
789
790 /* No problem storing the pid here, as it is still in Vprocess_alist. */
791 deleted_pid_list = Fcons (make_fixnum_or_float (pid),
792 /* GC treated elements set to nil. */
793 Fdelq (Qnil, deleted_pid_list));
794 /* If the process has already signaled, remove it from the list. */
795 if (p->raw_status_new)
796 update_status (p);
797 symbol = p->status;
798 if (CONSP (p->status))
799 symbol = XCAR (p->status);
800 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit))
801 deleted_pid_list
802 = Fdelete (make_fixnum_or_float (pid), deleted_pid_list);
803 else
804 #endif
805 {
806 Fkill_process (process, Qnil);
807 /* Do this now, since remove_process will make sigchld_handler do nothing. */
808 p->status
809 = Fcons (Qsignal, Fcons (make_number (SIGKILL), Qnil));
810 p->tick = ++process_tick;
811 status_notify (p);
812 }
813 }
814 remove_process (process);
815 return Qnil;
816 }
817 \f
818 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
819 doc: /* Return the status of PROCESS.
820 The returned value is one of the following symbols:
821 run -- for a process that is running.
822 stop -- for a process stopped but continuable.
823 exit -- for a process that has exited.
824 signal -- for a process that has got a fatal signal.
825 open -- for a network stream connection that is open.
826 listen -- for a network stream server that is listening.
827 closed -- for a network stream connection that is closed.
828 connect -- when waiting for a non-blocking connection to complete.
829 failed -- when a non-blocking connection has failed.
830 nil -- if arg is a process name and no such process exists.
831 PROCESS may be a process, a buffer, the name of a process, or
832 nil, indicating the current buffer's process. */)
833 (process)
834 register Lisp_Object process;
835 {
836 register struct Lisp_Process *p;
837 register Lisp_Object status;
838
839 if (STRINGP (process))
840 process = Fget_process (process);
841 else
842 process = get_process (process);
843
844 if (NILP (process))
845 return process;
846
847 p = XPROCESS (process);
848 if (p->raw_status_new)
849 update_status (p);
850 status = p->status;
851 if (CONSP (status))
852 status = XCAR (status);
853 if (NETCONN1_P (p) || SERIALCONN1_P (p))
854 {
855 if (EQ (status, Qexit))
856 status = Qclosed;
857 else if (EQ (p->command, Qt))
858 status = Qstop;
859 else if (EQ (status, Qrun))
860 status = Qopen;
861 }
862 return status;
863 }
864
865 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
866 1, 1, 0,
867 doc: /* Return the exit status of PROCESS or the signal number that killed it.
868 If PROCESS has not yet exited or died, return 0. */)
869 (process)
870 register Lisp_Object process;
871 {
872 CHECK_PROCESS (process);
873 if (XPROCESS (process)->raw_status_new)
874 update_status (XPROCESS (process));
875 if (CONSP (XPROCESS (process)->status))
876 return XCAR (XCDR (XPROCESS (process)->status));
877 return make_number (0);
878 }
879
880 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
881 doc: /* Return the process id of PROCESS.
882 This is the pid of the external process which PROCESS uses or talks to.
883 For a network connection, this value is nil. */)
884 (process)
885 register Lisp_Object process;
886 {
887 /* Assignment to EMACS_INT stops GCC whining about limited range of
888 data type. */
889 EMACS_INT pid;
890
891 CHECK_PROCESS (process);
892 pid = XPROCESS (process)->pid;
893 return (pid ? make_fixnum_or_float (pid) : Qnil);
894 }
895
896 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
897 doc: /* Return the name of PROCESS, as a string.
898 This is the name of the program invoked in PROCESS,
899 possibly modified to make it unique among process names. */)
900 (process)
901 register Lisp_Object process;
902 {
903 CHECK_PROCESS (process);
904 return XPROCESS (process)->name;
905 }
906
907 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
908 doc: /* Return the command that was executed to start PROCESS.
909 This is a list of strings, the first string being the program executed
910 and the rest of the strings being the arguments given to it.
911 For a network or serial process, this is nil (process is running) or t
912 \(process is stopped). */)
913 (process)
914 register Lisp_Object process;
915 {
916 CHECK_PROCESS (process);
917 return XPROCESS (process)->command;
918 }
919
920 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
921 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
922 This is the terminal that the process itself reads and writes on,
923 not the name of the pty that Emacs uses to talk with that terminal. */)
924 (process)
925 register Lisp_Object process;
926 {
927 CHECK_PROCESS (process);
928 return XPROCESS (process)->tty_name;
929 }
930
931 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
932 2, 2, 0,
933 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil). */)
934 (process, buffer)
935 register Lisp_Object process, buffer;
936 {
937 struct Lisp_Process *p;
938
939 CHECK_PROCESS (process);
940 if (!NILP (buffer))
941 CHECK_BUFFER (buffer);
942 p = XPROCESS (process);
943 p->buffer = buffer;
944 if (NETCONN1_P (p) || SERIALCONN1_P (p))
945 p->childp = Fplist_put (p->childp, QCbuffer, buffer);
946 setup_process_coding_systems (process);
947 return buffer;
948 }
949
950 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
951 1, 1, 0,
952 doc: /* Return the buffer PROCESS is associated with.
953 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
954 (process)
955 register Lisp_Object process;
956 {
957 CHECK_PROCESS (process);
958 return XPROCESS (process)->buffer;
959 }
960
961 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
962 1, 1, 0,
963 doc: /* Return the marker for the end of the last output from PROCESS. */)
964 (process)
965 register Lisp_Object process;
966 {
967 CHECK_PROCESS (process);
968 return XPROCESS (process)->mark;
969 }
970
971 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
972 2, 2, 0,
973 doc: /* Give PROCESS the filter function FILTER; nil means no filter.
974 A value of t means stop accepting output from the process.
975
976 When a process has a filter, its buffer is not used for output.
977 Instead, each time it does output, the entire string of output is
978 passed to the filter.
979
980 The filter gets two arguments: the process and the string of output.
981 The string argument is normally a multibyte string, except:
982 - if the process' input coding system is no-conversion or raw-text,
983 it is a unibyte string (the non-converted input), or else
984 - if `default-enable-multibyte-characters' is nil, it is a unibyte
985 string (the result of converting the decoded input multibyte
986 string to unibyte with `string-make-unibyte'). */)
987 (process, filter)
988 register Lisp_Object process, filter;
989 {
990 struct Lisp_Process *p;
991
992 CHECK_PROCESS (process);
993 p = XPROCESS (process);
994
995 /* Don't signal an error if the process' input file descriptor
996 is closed. This could make debugging Lisp more difficult,
997 for example when doing something like
998
999 (setq process (start-process ...))
1000 (debug)
1001 (set-process-filter process ...) */
1002
1003 if (p->infd >= 0)
1004 {
1005 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1006 {
1007 FD_CLR (p->infd, &input_wait_mask);
1008 FD_CLR (p->infd, &non_keyboard_wait_mask);
1009 }
1010 else if (EQ (p->filter, Qt)
1011 /* Network or serial process not stopped: */
1012 && !EQ (p->command, Qt))
1013 {
1014 FD_SET (p->infd, &input_wait_mask);
1015 FD_SET (p->infd, &non_keyboard_wait_mask);
1016 }
1017 }
1018
1019 p->filter = filter;
1020 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1021 p->childp = Fplist_put (p->childp, QCfilter, filter);
1022 setup_process_coding_systems (process);
1023 return filter;
1024 }
1025
1026 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1027 1, 1, 0,
1028 doc: /* Returns the filter function of PROCESS; nil if none.
1029 See `set-process-filter' for more info on filter functions. */)
1030 (process)
1031 register Lisp_Object process;
1032 {
1033 CHECK_PROCESS (process);
1034 return XPROCESS (process)->filter;
1035 }
1036
1037 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1038 2, 2, 0,
1039 doc: /* Give PROCESS the sentinel SENTINEL; nil for none.
1040 The sentinel is called as a function when the process changes state.
1041 It gets two arguments: the process, and a string describing the change. */)
1042 (process, sentinel)
1043 register Lisp_Object process, sentinel;
1044 {
1045 struct Lisp_Process *p;
1046
1047 CHECK_PROCESS (process);
1048 p = XPROCESS (process);
1049
1050 p->sentinel = sentinel;
1051 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1052 p->childp = Fplist_put (p->childp, QCsentinel, sentinel);
1053 return sentinel;
1054 }
1055
1056 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1057 1, 1, 0,
1058 doc: /* Return the sentinel of PROCESS; nil if none.
1059 See `set-process-sentinel' for more info on sentinels. */)
1060 (process)
1061 register Lisp_Object process;
1062 {
1063 CHECK_PROCESS (process);
1064 return XPROCESS (process)->sentinel;
1065 }
1066
1067 DEFUN ("set-process-window-size", Fset_process_window_size,
1068 Sset_process_window_size, 3, 3, 0,
1069 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1070 (process, height, width)
1071 register Lisp_Object process, height, width;
1072 {
1073 CHECK_PROCESS (process);
1074 CHECK_NATNUM (height);
1075 CHECK_NATNUM (width);
1076
1077 if (XPROCESS (process)->infd < 0
1078 || set_window_size (XPROCESS (process)->infd,
1079 XINT (height), XINT (width)) <= 0)
1080 return Qnil;
1081 else
1082 return Qt;
1083 }
1084
1085 DEFUN ("set-process-inherit-coding-system-flag",
1086 Fset_process_inherit_coding_system_flag,
1087 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1088 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1089 If the second argument FLAG is non-nil, then the variable
1090 `buffer-file-coding-system' of the buffer associated with PROCESS
1091 will be bound to the value of the coding system used to decode
1092 the process output.
1093
1094 This is useful when the coding system specified for the process buffer
1095 leaves either the character code conversion or the end-of-line conversion
1096 unspecified, or if the coding system used to decode the process output
1097 is more appropriate for saving the process buffer.
1098
1099 Binding the variable `inherit-process-coding-system' to non-nil before
1100 starting the process is an alternative way of setting the inherit flag
1101 for the process which will run. */)
1102 (process, flag)
1103 register Lisp_Object process, flag;
1104 {
1105 CHECK_PROCESS (process);
1106 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1107 return flag;
1108 }
1109
1110 DEFUN ("process-inherit-coding-system-flag",
1111 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
1112 1, 1, 0,
1113 doc: /* Return the value of inherit-coding-system flag for PROCESS.
1114 If this flag is t, `buffer-file-coding-system' of the buffer
1115 associated with PROCESS will inherit the coding system used to decode
1116 the process output. */)
1117 (process)
1118 register Lisp_Object process;
1119 {
1120 CHECK_PROCESS (process);
1121 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
1122 }
1123
1124 DEFUN ("set-process-query-on-exit-flag",
1125 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1126 2, 2, 0,
1127 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1128 If the second argument FLAG is non-nil, Emacs will query the user before
1129 exiting if PROCESS is running. */)
1130 (process, flag)
1131 register Lisp_Object process, flag;
1132 {
1133 CHECK_PROCESS (process);
1134 XPROCESS (process)->kill_without_query = NILP (flag);
1135 return flag;
1136 }
1137
1138 DEFUN ("process-query-on-exit-flag",
1139 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1140 1, 1, 0,
1141 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1142 (process)
1143 register Lisp_Object process;
1144 {
1145 CHECK_PROCESS (process);
1146 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1147 }
1148
1149 #ifdef DATAGRAM_SOCKETS
1150 Lisp_Object Fprocess_datagram_address ();
1151 #endif
1152
1153 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1154 1, 2, 0,
1155 doc: /* Return the contact info of PROCESS; t for a real child.
1156 For a network or serial connection, the value depends on the optional
1157 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1158 SERVICE) for a network connection or (PORT SPEED) for a serial
1159 connection. If KEY is t, the complete contact information for the
1160 connection is returned, else the specific value for the keyword KEY is
1161 returned. See `make-network-process' or `make-serial-process' for a
1162 list of keywords. */)
1163 (process, key)
1164 register Lisp_Object process, key;
1165 {
1166 Lisp_Object contact;
1167
1168 CHECK_PROCESS (process);
1169 contact = XPROCESS (process)->childp;
1170
1171 #ifdef DATAGRAM_SOCKETS
1172 if (DATAGRAM_CONN_P (process)
1173 && (EQ (key, Qt) || EQ (key, QCremote)))
1174 contact = Fplist_put (contact, QCremote,
1175 Fprocess_datagram_address (process));
1176 #endif
1177
1178 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1179 return contact;
1180 if (NILP (key) && NETCONN_P (process))
1181 return Fcons (Fplist_get (contact, QChost),
1182 Fcons (Fplist_get (contact, QCservice), Qnil));
1183 if (NILP (key) && SERIALCONN_P (process))
1184 return Fcons (Fplist_get (contact, QCport),
1185 Fcons (Fplist_get (contact, QCspeed), Qnil));
1186 return Fplist_get (contact, key);
1187 }
1188
1189 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1190 1, 1, 0,
1191 doc: /* Return the plist of PROCESS. */)
1192 (process)
1193 register Lisp_Object process;
1194 {
1195 CHECK_PROCESS (process);
1196 return XPROCESS (process)->plist;
1197 }
1198
1199 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1200 2, 2, 0,
1201 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1202 (process, plist)
1203 register Lisp_Object process, plist;
1204 {
1205 CHECK_PROCESS (process);
1206 CHECK_LIST (plist);
1207
1208 XPROCESS (process)->plist = plist;
1209 return plist;
1210 }
1211
1212 #if 0 /* Turned off because we don't currently record this info
1213 in the process. Perhaps add it. */
1214 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1215 doc: /* Return the connection type of PROCESS.
1216 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1217 a socket connection. */)
1218 (process)
1219 Lisp_Object process;
1220 {
1221 return XPROCESS (process)->type;
1222 }
1223 #endif
1224
1225 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1226 doc: /* Return the connection type of PROCESS.
1227 The value is either the symbol `real', `network', or `serial'.
1228 PROCESS may be a process, a buffer, the name of a process or buffer, or
1229 nil, indicating the current buffer's process. */)
1230 (process)
1231 Lisp_Object process;
1232 {
1233 Lisp_Object proc;
1234 proc = get_process (process);
1235 return XPROCESS (proc)->type;
1236 }
1237
1238 #ifdef HAVE_SOCKETS
1239 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1240 1, 2, 0,
1241 doc: /* Convert network ADDRESS from internal format to a string.
1242 A 4 or 5 element vector represents an IPv4 address (with port number).
1243 An 8 or 9 element vector represents an IPv6 address (with port number).
1244 If optional second argument OMIT-PORT is non-nil, don't include a port
1245 number in the string, even when present in ADDRESS.
1246 Returns nil if format of ADDRESS is invalid. */)
1247 (address, omit_port)
1248 Lisp_Object address, omit_port;
1249 {
1250 if (NILP (address))
1251 return Qnil;
1252
1253 if (STRINGP (address)) /* AF_LOCAL */
1254 return address;
1255
1256 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1257 {
1258 register struct Lisp_Vector *p = XVECTOR (address);
1259 Lisp_Object args[10];
1260 int nargs, i;
1261
1262 if (p->size == 4 || (p->size == 5 && !NILP (omit_port)))
1263 {
1264 args[0] = build_string ("%d.%d.%d.%d");
1265 nargs = 4;
1266 }
1267 else if (p->size == 5)
1268 {
1269 args[0] = build_string ("%d.%d.%d.%d:%d");
1270 nargs = 5;
1271 }
1272 else if (p->size == 8 || (p->size == 9 && !NILP (omit_port)))
1273 {
1274 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1275 nargs = 8;
1276 }
1277 else if (p->size == 9)
1278 {
1279 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1280 nargs = 9;
1281 }
1282 else
1283 return Qnil;
1284
1285 for (i = 0; i < nargs; i++)
1286 {
1287 EMACS_INT element = XINT (p->contents[i]);
1288
1289 if (element < 0 || element > 65535)
1290 return Qnil;
1291
1292 if (nargs <= 5 /* IPv4 */
1293 && i < 4 /* host, not port */
1294 && element > 255)
1295 return Qnil;
1296
1297 args[i+1] = p->contents[i];
1298 }
1299
1300 return Fformat (nargs+1, args);
1301 }
1302
1303 if (CONSP (address))
1304 {
1305 Lisp_Object args[2];
1306 args[0] = build_string ("<Family %d>");
1307 args[1] = Fcar (address);
1308 return Fformat (2, args);
1309 }
1310
1311 return Qnil;
1312 }
1313 #endif
1314 \f
1315 static Lisp_Object
1316 list_processes_1 (query_only)
1317 Lisp_Object query_only;
1318 {
1319 register Lisp_Object tail, tem;
1320 Lisp_Object proc, minspace, tem1;
1321 register struct Lisp_Process *p;
1322 char tembuf[300];
1323 int w_proc, w_buffer, w_tty;
1324 int exited = 0;
1325 Lisp_Object i_status, i_buffer, i_tty, i_command;
1326
1327 w_proc = 4; /* Proc */
1328 w_buffer = 6; /* Buffer */
1329 w_tty = 0; /* Omit if no ttys */
1330
1331 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1332 {
1333 int i;
1334
1335 proc = Fcdr (XCAR (tail));
1336 p = XPROCESS (proc);
1337 if (NILP (p->type))
1338 continue;
1339 if (!NILP (query_only) && p->kill_without_query)
1340 continue;
1341 if (STRINGP (p->name)
1342 && ( i = SCHARS (p->name), (i > w_proc)))
1343 w_proc = i;
1344 if (!NILP (p->buffer))
1345 {
1346 if (NILP (XBUFFER (p->buffer)->name))
1347 {
1348 if (w_buffer < 8)
1349 w_buffer = 8; /* (Killed) */
1350 }
1351 else if ((i = SCHARS (XBUFFER (p->buffer)->name), (i > w_buffer)))
1352 w_buffer = i;
1353 }
1354 if (STRINGP (p->tty_name)
1355 && (i = SCHARS (p->tty_name), (i > w_tty)))
1356 w_tty = i;
1357 }
1358
1359 XSETFASTINT (i_status, w_proc + 1);
1360 XSETFASTINT (i_buffer, XFASTINT (i_status) + 9);
1361 if (w_tty)
1362 {
1363 XSETFASTINT (i_tty, XFASTINT (i_buffer) + w_buffer + 1);
1364 XSETFASTINT (i_command, XFASTINT (i_tty) + w_tty + 1);
1365 }
1366 else
1367 {
1368 i_tty = Qnil;
1369 XSETFASTINT (i_command, XFASTINT (i_buffer) + w_buffer + 1);
1370 }
1371
1372 XSETFASTINT (minspace, 1);
1373
1374 set_buffer_internal (XBUFFER (Vstandard_output));
1375 current_buffer->undo_list = Qt;
1376
1377 current_buffer->truncate_lines = Qt;
1378
1379 write_string ("Proc", -1);
1380 Findent_to (i_status, minspace); write_string ("Status", -1);
1381 Findent_to (i_buffer, minspace); write_string ("Buffer", -1);
1382 if (!NILP (i_tty))
1383 {
1384 Findent_to (i_tty, minspace); write_string ("Tty", -1);
1385 }
1386 Findent_to (i_command, minspace); write_string ("Command", -1);
1387 write_string ("\n", -1);
1388
1389 write_string ("----", -1);
1390 Findent_to (i_status, minspace); write_string ("------", -1);
1391 Findent_to (i_buffer, minspace); write_string ("------", -1);
1392 if (!NILP (i_tty))
1393 {
1394 Findent_to (i_tty, minspace); write_string ("---", -1);
1395 }
1396 Findent_to (i_command, minspace); write_string ("-------", -1);
1397 write_string ("\n", -1);
1398
1399 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1400 {
1401 Lisp_Object symbol;
1402
1403 proc = Fcdr (XCAR (tail));
1404 p = XPROCESS (proc);
1405 if (NILP (p->type))
1406 continue;
1407 if (!NILP (query_only) && p->kill_without_query)
1408 continue;
1409
1410 Finsert (1, &p->name);
1411 Findent_to (i_status, minspace);
1412
1413 if (p->raw_status_new)
1414 update_status (p);
1415 symbol = p->status;
1416 if (CONSP (p->status))
1417 symbol = XCAR (p->status);
1418
1419 if (EQ (symbol, Qsignal))
1420 {
1421 Lisp_Object tem;
1422 tem = Fcar (Fcdr (p->status));
1423 Fprinc (symbol, Qnil);
1424 }
1425 else if (NETCONN1_P (p) || SERIALCONN1_P (p))
1426 {
1427 if (EQ (symbol, Qexit))
1428 write_string ("closed", -1);
1429 else if (EQ (p->command, Qt))
1430 write_string ("stopped", -1);
1431 else if (EQ (symbol, Qrun))
1432 write_string ("open", -1);
1433 else
1434 Fprinc (symbol, Qnil);
1435 }
1436 else if (SERIALCONN1_P (p))
1437 {
1438 write_string ("running", -1);
1439 }
1440 else
1441 Fprinc (symbol, Qnil);
1442
1443 if (EQ (symbol, Qexit))
1444 {
1445 Lisp_Object tem;
1446 tem = Fcar (Fcdr (p->status));
1447 if (XFASTINT (tem))
1448 {
1449 sprintf (tembuf, " %d", (int) XFASTINT (tem));
1450 write_string (tembuf, -1);
1451 }
1452 }
1453
1454 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit) || EQ (symbol, Qclosed))
1455 exited++;
1456
1457 Findent_to (i_buffer, minspace);
1458 if (NILP (p->buffer))
1459 insert_string ("(none)");
1460 else if (NILP (XBUFFER (p->buffer)->name))
1461 insert_string ("(Killed)");
1462 else
1463 Finsert (1, &XBUFFER (p->buffer)->name);
1464
1465 if (!NILP (i_tty))
1466 {
1467 Findent_to (i_tty, minspace);
1468 if (STRINGP (p->tty_name))
1469 Finsert (1, &p->tty_name);
1470 }
1471
1472 Findent_to (i_command, minspace);
1473
1474 if (EQ (p->status, Qlisten))
1475 {
1476 Lisp_Object port = Fplist_get (p->childp, QCservice);
1477 if (INTEGERP (port))
1478 port = Fnumber_to_string (port);
1479 if (NILP (port))
1480 port = Fformat_network_address (Fplist_get (p->childp, QClocal), Qnil);
1481 sprintf (tembuf, "(network %s server on %s)\n",
1482 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1483 (STRINGP (port) ? (char *)SDATA (port) : "?"));
1484 insert_string (tembuf);
1485 }
1486 else if (NETCONN1_P (p))
1487 {
1488 /* For a local socket, there is no host name,
1489 so display service instead. */
1490 Lisp_Object host = Fplist_get (p->childp, QChost);
1491 if (!STRINGP (host))
1492 {
1493 host = Fplist_get (p->childp, QCservice);
1494 if (INTEGERP (host))
1495 host = Fnumber_to_string (host);
1496 }
1497 if (NILP (host))
1498 host = Fformat_network_address (Fplist_get (p->childp, QCremote), Qnil);
1499 sprintf (tembuf, "(network %s connection to %s)\n",
1500 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1501 (STRINGP (host) ? (char *)SDATA (host) : "?"));
1502 insert_string (tembuf);
1503 }
1504 else if (SERIALCONN1_P (p))
1505 {
1506 Lisp_Object port = Fplist_get (p->childp, QCport);
1507 Lisp_Object speed = Fplist_get (p->childp, QCspeed);
1508 insert_string ("(serial port ");
1509 if (STRINGP (port))
1510 insert_string (SDATA (port));
1511 else
1512 insert_string ("?");
1513 if (INTEGERP (speed))
1514 {
1515 sprintf (tembuf, " at %d b/s", XINT (speed));
1516 insert_string (tembuf);
1517 }
1518 insert_string (")\n");
1519 }
1520 else
1521 {
1522 tem = p->command;
1523 while (1)
1524 {
1525 tem1 = Fcar (tem);
1526 Finsert (1, &tem1);
1527 tem = Fcdr (tem);
1528 if (NILP (tem))
1529 break;
1530 insert_string (" ");
1531 }
1532 insert_string ("\n");
1533 }
1534 }
1535 if (exited)
1536 status_notify (NULL);
1537 return Qnil;
1538 }
1539
1540 DEFUN ("list-processes", Flist_processes, Slist_processes, 0, 1, "P",
1541 doc: /* Display a list of all processes.
1542 If optional argument QUERY-ONLY is non-nil, only processes with
1543 the query-on-exit flag set will be listed.
1544 Any process listed as exited or signaled is actually eliminated
1545 after the listing is made. */)
1546 (query_only)
1547 Lisp_Object query_only;
1548 {
1549 internal_with_output_to_temp_buffer ("*Process List*",
1550 list_processes_1, query_only);
1551 return Qnil;
1552 }
1553
1554 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1555 doc: /* Return a list of all processes. */)
1556 ()
1557 {
1558 return Fmapcar (Qcdr, Vprocess_alist);
1559 }
1560 \f
1561 /* Starting asynchronous inferior processes. */
1562
1563 static Lisp_Object start_process_unwind ();
1564
1565 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1566 doc: /* Start a program in a subprocess. Return the process object for it.
1567 NAME is name for process. It is modified if necessary to make it unique.
1568 BUFFER is the buffer (or buffer name) to associate with the process.
1569
1570 Process output (both standard output and standard error streams) goes
1571 at end of BUFFER, unless you specify an output stream or filter
1572 function to handle the output. BUFFER may also be nil, meaning that
1573 this process is not associated with any buffer.
1574
1575 PROGRAM is the program file name. It is searched for in PATH.
1576 Remaining arguments are strings to give program as arguments.
1577
1578 If you want to separate standard output from standard error, invoke
1579 the command through a shell and redirect one of them using the shell
1580 syntax.
1581
1582 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1583 (nargs, args)
1584 int nargs;
1585 register Lisp_Object *args;
1586 {
1587 Lisp_Object buffer, name, program, proc, current_dir, tem;
1588 register unsigned char **new_argv;
1589 register int i;
1590 int count = SPECPDL_INDEX ();
1591
1592 buffer = args[1];
1593 if (!NILP (buffer))
1594 buffer = Fget_buffer_create (buffer);
1595
1596 /* Make sure that the child will be able to chdir to the current
1597 buffer's current directory, or its unhandled equivalent. We
1598 can't just have the child check for an error when it does the
1599 chdir, since it's in a vfork.
1600
1601 We have to GCPRO around this because Fexpand_file_name and
1602 Funhandled_file_name_directory might call a file name handling
1603 function. The argument list is protected by the caller, so all
1604 we really have to worry about is buffer. */
1605 {
1606 struct gcpro gcpro1, gcpro2;
1607
1608 current_dir = current_buffer->directory;
1609
1610 GCPRO2 (buffer, current_dir);
1611
1612 current_dir = Funhandled_file_name_directory (current_dir);
1613 if (NILP (current_dir))
1614 /* If the file name handler says that current_dir is unreachable, use
1615 a sensible default. */
1616 current_dir = build_string ("~/");
1617 current_dir = expand_and_dir_to_file (current_dir, Qnil);
1618 if (NILP (Ffile_accessible_directory_p (current_dir)))
1619 report_file_error ("Setting current directory",
1620 Fcons (current_buffer->directory, Qnil));
1621
1622 UNGCPRO;
1623 }
1624
1625 name = args[0];
1626 CHECK_STRING (name);
1627
1628 program = args[2];
1629
1630 CHECK_STRING (program);
1631
1632 proc = make_process (name);
1633 /* If an error occurs and we can't start the process, we want to
1634 remove it from the process list. This means that each error
1635 check in create_process doesn't need to call remove_process
1636 itself; it's all taken care of here. */
1637 record_unwind_protect (start_process_unwind, proc);
1638
1639 XPROCESS (proc)->childp = Qt;
1640 XPROCESS (proc)->plist = Qnil;
1641 XPROCESS (proc)->type = Qreal;
1642 XPROCESS (proc)->buffer = buffer;
1643 XPROCESS (proc)->sentinel = Qnil;
1644 XPROCESS (proc)->filter = Qnil;
1645 XPROCESS (proc)->command = Flist (nargs - 2, args + 2);
1646
1647 #ifdef ADAPTIVE_READ_BUFFERING
1648 XPROCESS (proc)->adaptive_read_buffering
1649 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1650 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1651 #endif
1652
1653 /* Make the process marker point into the process buffer (if any). */
1654 if (BUFFERP (buffer))
1655 set_marker_both (XPROCESS (proc)->mark, buffer,
1656 BUF_ZV (XBUFFER (buffer)),
1657 BUF_ZV_BYTE (XBUFFER (buffer)));
1658
1659 {
1660 /* Decide coding systems for communicating with the process. Here
1661 we don't setup the structure coding_system nor pay attention to
1662 unibyte mode. They are done in create_process. */
1663
1664 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1665 Lisp_Object coding_systems = Qt;
1666 Lisp_Object val, *args2;
1667 struct gcpro gcpro1, gcpro2;
1668
1669 val = Vcoding_system_for_read;
1670 if (NILP (val))
1671 {
1672 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
1673 args2[0] = Qstart_process;
1674 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1675 GCPRO2 (proc, current_dir);
1676 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1677 UNGCPRO;
1678 if (CONSP (coding_systems))
1679 val = XCAR (coding_systems);
1680 else if (CONSP (Vdefault_process_coding_system))
1681 val = XCAR (Vdefault_process_coding_system);
1682 }
1683 XPROCESS (proc)->decode_coding_system = val;
1684
1685 val = Vcoding_system_for_write;
1686 if (NILP (val))
1687 {
1688 if (EQ (coding_systems, Qt))
1689 {
1690 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof args2);
1691 args2[0] = Qstart_process;
1692 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1693 GCPRO2 (proc, current_dir);
1694 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1695 UNGCPRO;
1696 }
1697 if (CONSP (coding_systems))
1698 val = XCDR (coding_systems);
1699 else if (CONSP (Vdefault_process_coding_system))
1700 val = XCDR (Vdefault_process_coding_system);
1701 }
1702 XPROCESS (proc)->encode_coding_system = val;
1703 }
1704
1705 new_argv = (unsigned char **) alloca ((nargs - 1) * sizeof (char *));
1706
1707 /* If program file name is not absolute, search our path for it.
1708 Put the name we will really use in TEM. */
1709 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1710 && !(SCHARS (program) > 1
1711 && IS_DEVICE_SEP (SREF (program, 1))))
1712 {
1713 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1714
1715 tem = Qnil;
1716 GCPRO4 (name, program, buffer, current_dir);
1717 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1718 UNGCPRO;
1719 if (NILP (tem))
1720 report_file_error ("Searching for program", Fcons (program, Qnil));
1721 tem = Fexpand_file_name (tem, Qnil);
1722 }
1723 else
1724 {
1725 if (!NILP (Ffile_directory_p (program)))
1726 error ("Specified program for new process is a directory");
1727 tem = program;
1728 }
1729
1730 /* If program file name starts with /: for quoting a magic name,
1731 discard that. */
1732 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1733 && SREF (tem, 1) == ':')
1734 tem = Fsubstring (tem, make_number (2), Qnil);
1735
1736 /* Encode the file name and put it in NEW_ARGV.
1737 That's where the child will use it to execute the program. */
1738 tem = ENCODE_FILE (tem);
1739 new_argv[0] = SDATA (tem);
1740
1741 /* Here we encode arguments by the coding system used for sending
1742 data to the process. We don't support using different coding
1743 systems for encoding arguments and for encoding data sent to the
1744 process. */
1745
1746 for (i = 3; i < nargs; i++)
1747 {
1748 tem = args[i];
1749 CHECK_STRING (tem);
1750 if (STRING_MULTIBYTE (tem))
1751 tem = (code_convert_string_norecord
1752 (tem, XPROCESS (proc)->encode_coding_system, 1));
1753 new_argv[i - 2] = SDATA (tem);
1754 }
1755 new_argv[i - 2] = 0;
1756
1757 XPROCESS (proc)->decoding_buf = make_uninit_string (0);
1758 XPROCESS (proc)->decoding_carryover = 0;
1759 XPROCESS (proc)->encoding_buf = make_uninit_string (0);
1760
1761 XPROCESS (proc)->inherit_coding_system_flag
1762 = !(NILP (buffer) || !inherit_process_coding_system);
1763
1764 create_process (proc, (char **) new_argv, current_dir);
1765
1766 return unbind_to (count, proc);
1767 }
1768
1769 /* This function is the unwind_protect form for Fstart_process. If
1770 PROC doesn't have its pid set, then we know someone has signaled
1771 an error and the process wasn't started successfully, so we should
1772 remove it from the process list. */
1773 static Lisp_Object
1774 start_process_unwind (proc)
1775 Lisp_Object proc;
1776 {
1777 if (!PROCESSP (proc))
1778 abort ();
1779
1780 /* Was PROC started successfully? */
1781 if (XPROCESS (proc)->pid <= 0)
1782 remove_process (proc);
1783
1784 return Qnil;
1785 }
1786
1787 static void
1788 create_process_1 (timer)
1789 struct atimer *timer;
1790 {
1791 /* Nothing to do. */
1792 }
1793
1794
1795 #if 0 /* This doesn't work; see the note before sigchld_handler. */
1796 #ifdef USG
1797 #ifdef SIGCHLD
1798 /* Mimic blocking of signals on system V, which doesn't really have it. */
1799
1800 /* Nonzero means we got a SIGCHLD when it was supposed to be blocked. */
1801 int sigchld_deferred;
1802
1803 SIGTYPE
1804 create_process_sigchld ()
1805 {
1806 signal (SIGCHLD, create_process_sigchld);
1807
1808 sigchld_deferred = 1;
1809 }
1810 #endif
1811 #endif
1812 #endif
1813
1814 void
1815 create_process (process, new_argv, current_dir)
1816 Lisp_Object process;
1817 char **new_argv;
1818 Lisp_Object current_dir;
1819 {
1820 int inchannel, outchannel;
1821 pid_t pid;
1822 int sv[2];
1823 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1824 int wait_child_setup[2];
1825 #endif
1826 #ifdef POSIX_SIGNALS
1827 sigset_t procmask;
1828 sigset_t blocked;
1829 struct sigaction sigint_action;
1830 struct sigaction sigquit_action;
1831 #ifdef AIX
1832 struct sigaction sighup_action;
1833 #endif
1834 #else /* !POSIX_SIGNALS */
1835 #if 0
1836 #ifdef SIGCHLD
1837 SIGTYPE (*sigchld)();
1838 #endif
1839 #endif /* 0 */
1840 #endif /* !POSIX_SIGNALS */
1841 /* Use volatile to protect variables from being clobbered by longjmp. */
1842 volatile int forkin, forkout;
1843 volatile int pty_flag = 0;
1844 #ifndef USE_CRT_DLL
1845 extern char **environ;
1846 #endif
1847
1848 inchannel = outchannel = -1;
1849
1850 #ifdef HAVE_PTYS
1851 if (!NILP (Vprocess_connection_type))
1852 outchannel = inchannel = allocate_pty ();
1853
1854 if (inchannel >= 0)
1855 {
1856 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1857 /* On most USG systems it does not work to open the pty's tty here,
1858 then close it and reopen it in the child. */
1859 #ifdef O_NOCTTY
1860 /* Don't let this terminal become our controlling terminal
1861 (in case we don't have one). */
1862 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1863 #else
1864 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
1865 #endif
1866 if (forkin < 0)
1867 report_file_error ("Opening pty", Qnil);
1868 #if defined (DONT_REOPEN_PTY)
1869 /* In the case that vfork is defined as fork, the parent process
1870 (Emacs) may send some data before the child process completes
1871 tty options setup. So we setup tty before forking. */
1872 child_setup_tty (forkout);
1873 #endif /* DONT_REOPEN_PTY */
1874 #else
1875 forkin = forkout = -1;
1876 #endif /* not USG, or USG_SUBTTY_WORKS */
1877 pty_flag = 1;
1878 }
1879 else
1880 #endif /* HAVE_PTYS */
1881 {
1882 int tem;
1883 tem = pipe (sv);
1884 if (tem < 0)
1885 report_file_error ("Creating pipe", Qnil);
1886 inchannel = sv[0];
1887 forkout = sv[1];
1888 tem = pipe (sv);
1889 if (tem < 0)
1890 {
1891 emacs_close (inchannel);
1892 emacs_close (forkout);
1893 report_file_error ("Creating pipe", Qnil);
1894 }
1895 outchannel = sv[1];
1896 forkin = sv[0];
1897 }
1898
1899 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1900 {
1901 int tem;
1902
1903 tem = pipe (wait_child_setup);
1904 if (tem < 0)
1905 report_file_error ("Creating pipe", Qnil);
1906 tem = fcntl (wait_child_setup[1], F_GETFD, 0);
1907 if (tem >= 0)
1908 tem = fcntl (wait_child_setup[1], F_SETFD, tem | FD_CLOEXEC);
1909 if (tem < 0)
1910 {
1911 emacs_close (wait_child_setup[0]);
1912 emacs_close (wait_child_setup[1]);
1913 report_file_error ("Setting file descriptor flags", Qnil);
1914 }
1915 }
1916 #endif
1917
1918 #if 0
1919 /* Replaced by close_process_descs */
1920 set_exclusive_use (inchannel);
1921 set_exclusive_use (outchannel);
1922 #endif
1923
1924 #ifdef O_NONBLOCK
1925 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1926 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1927 #else
1928 #ifdef O_NDELAY
1929 fcntl (inchannel, F_SETFL, O_NDELAY);
1930 fcntl (outchannel, F_SETFL, O_NDELAY);
1931 #endif
1932 #endif
1933
1934 /* Record this as an active process, with its channels.
1935 As a result, child_setup will close Emacs's side of the pipes. */
1936 chan_process[inchannel] = process;
1937 XPROCESS (process)->infd = inchannel;
1938 XPROCESS (process)->outfd = outchannel;
1939
1940 /* Previously we recorded the tty descriptor used in the subprocess.
1941 It was only used for getting the foreground tty process, so now
1942 we just reopen the device (see emacs_get_tty_pgrp) as this is
1943 more portable (see USG_SUBTTY_WORKS above). */
1944
1945 XPROCESS (process)->pty_flag = pty_flag;
1946 XPROCESS (process)->status = Qrun;
1947 setup_process_coding_systems (process);
1948
1949 /* Delay interrupts until we have a chance to store
1950 the new fork's pid in its process structure */
1951 #ifdef POSIX_SIGNALS
1952 sigemptyset (&blocked);
1953 #ifdef SIGCHLD
1954 sigaddset (&blocked, SIGCHLD);
1955 #endif
1956 #ifdef HAVE_WORKING_VFORK
1957 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
1958 this sets the parent's signal handlers as well as the child's.
1959 So delay all interrupts whose handlers the child might munge,
1960 and record the current handlers so they can be restored later. */
1961 sigaddset (&blocked, SIGINT ); sigaction (SIGINT , 0, &sigint_action );
1962 sigaddset (&blocked, SIGQUIT); sigaction (SIGQUIT, 0, &sigquit_action);
1963 #ifdef AIX
1964 sigaddset (&blocked, SIGHUP ); sigaction (SIGHUP , 0, &sighup_action );
1965 #endif
1966 #endif /* HAVE_WORKING_VFORK */
1967 sigprocmask (SIG_BLOCK, &blocked, &procmask);
1968 #else /* !POSIX_SIGNALS */
1969 #ifdef SIGCHLD
1970 #if defined (BSD_SYSTEM) || defined (HPUX)
1971 sigsetmask (sigmask (SIGCHLD));
1972 #else /* ordinary USG */
1973 #if 0
1974 sigchld_deferred = 0;
1975 sigchld = signal (SIGCHLD, create_process_sigchld);
1976 #endif
1977 #endif /* ordinary USG */
1978 #endif /* SIGCHLD */
1979 #endif /* !POSIX_SIGNALS */
1980
1981 FD_SET (inchannel, &input_wait_mask);
1982 FD_SET (inchannel, &non_keyboard_wait_mask);
1983 if (inchannel > max_process_desc)
1984 max_process_desc = inchannel;
1985
1986 /* Until we store the proper pid, enable sigchld_handler
1987 to recognize an unknown pid as standing for this process.
1988 It is very important not to let this `marker' value stay
1989 in the table after this function has returned; if it does
1990 it might cause call-process to hang and subsequent asynchronous
1991 processes to get their return values scrambled. */
1992 XPROCESS (process)->pid = -1;
1993
1994 BLOCK_INPUT;
1995
1996 {
1997 /* child_setup must clobber environ on systems with true vfork.
1998 Protect it from permanent change. */
1999 char **save_environ = environ;
2000
2001 current_dir = ENCODE_FILE (current_dir);
2002
2003 #ifndef WINDOWSNT
2004 pid = vfork ();
2005 if (pid == 0)
2006 #endif /* not WINDOWSNT */
2007 {
2008 int xforkin = forkin;
2009 int xforkout = forkout;
2010
2011 #if 0 /* This was probably a mistake--it duplicates code later on,
2012 but fails to handle all the cases. */
2013 /* Make sure SIGCHLD is not blocked in the child. */
2014 sigsetmask (SIGEMPTYMASK);
2015 #endif
2016
2017 /* Make the pty be the controlling terminal of the process. */
2018 #ifdef HAVE_PTYS
2019 /* First, disconnect its current controlling terminal. */
2020 #ifdef HAVE_SETSID
2021 /* We tried doing setsid only if pty_flag, but it caused
2022 process_set_signal to fail on SGI when using a pipe. */
2023 setsid ();
2024 /* Make the pty's terminal the controlling terminal. */
2025 if (pty_flag)
2026 {
2027 #ifdef TIOCSCTTY
2028 /* We ignore the return value
2029 because faith@cs.unc.edu says that is necessary on Linux. */
2030 ioctl (xforkin, TIOCSCTTY, 0);
2031 #endif
2032 }
2033 #else /* not HAVE_SETSID */
2034 #ifdef USG
2035 /* It's very important to call setpgrp here and no time
2036 afterwards. Otherwise, we lose our controlling tty which
2037 is set when we open the pty. */
2038 setpgrp ();
2039 #endif /* USG */
2040 #endif /* not HAVE_SETSID */
2041 #if defined (HAVE_TERMIOS) && defined (LDISC1)
2042 if (pty_flag && xforkin >= 0)
2043 {
2044 struct termios t;
2045 tcgetattr (xforkin, &t);
2046 t.c_lflag = LDISC1;
2047 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
2048 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
2049 }
2050 #else
2051 #if defined (NTTYDISC) && defined (TIOCSETD)
2052 if (pty_flag && xforkin >= 0)
2053 {
2054 /* Use new line discipline. */
2055 int ldisc = NTTYDISC;
2056 ioctl (xforkin, TIOCSETD, &ldisc);
2057 }
2058 #endif
2059 #endif
2060 #ifdef TIOCNOTTY
2061 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
2062 can do TIOCSPGRP only to the process's controlling tty. */
2063 if (pty_flag)
2064 {
2065 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
2066 I can't test it since I don't have 4.3. */
2067 int j = emacs_open ("/dev/tty", O_RDWR, 0);
2068 ioctl (j, TIOCNOTTY, 0);
2069 emacs_close (j);
2070 #ifndef USG
2071 /* In order to get a controlling terminal on some versions
2072 of BSD, it is necessary to put the process in pgrp 0
2073 before it opens the terminal. */
2074 #ifdef HAVE_SETPGID
2075 setpgid (0, 0);
2076 #else
2077 setpgrp (0, 0);
2078 #endif
2079 #endif
2080 }
2081 #endif /* TIOCNOTTY */
2082
2083 #if !defined (DONT_REOPEN_PTY)
2084 /*** There is a suggestion that this ought to be a
2085 conditional on TIOCSPGRP,
2086 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
2087 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
2088 that system does seem to need this code, even though
2089 both HAVE_SETSID and TIOCSCTTY are defined. */
2090 /* Now close the pty (if we had it open) and reopen it.
2091 This makes the pty the controlling terminal of the subprocess. */
2092 if (pty_flag)
2093 {
2094
2095 /* I wonder if emacs_close (emacs_open (pty_name, ...))
2096 would work? */
2097 if (xforkin >= 0)
2098 emacs_close (xforkin);
2099 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
2100
2101 if (xforkin < 0)
2102 {
2103 emacs_write (1, "Couldn't open the pty terminal ", 31);
2104 emacs_write (1, pty_name, strlen (pty_name));
2105 emacs_write (1, "\n", 1);
2106 _exit (1);
2107 }
2108
2109 }
2110 #endif /* not DONT_REOPEN_PTY */
2111
2112 #ifdef SETUP_SLAVE_PTY
2113 if (pty_flag)
2114 {
2115 SETUP_SLAVE_PTY;
2116 }
2117 #endif /* SETUP_SLAVE_PTY */
2118 #ifdef AIX
2119 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
2120 Now reenable it in the child, so it will die when we want it to. */
2121 if (pty_flag)
2122 signal (SIGHUP, SIG_DFL);
2123 #endif
2124 #endif /* HAVE_PTYS */
2125
2126 signal (SIGINT, SIG_DFL);
2127 signal (SIGQUIT, SIG_DFL);
2128
2129 /* Stop blocking signals in the child. */
2130 #ifdef POSIX_SIGNALS
2131 sigprocmask (SIG_SETMASK, &procmask, 0);
2132 #else /* !POSIX_SIGNALS */
2133 #ifdef SIGCHLD
2134 #if defined (BSD_SYSTEM) || defined (HPUX)
2135 sigsetmask (SIGEMPTYMASK);
2136 #else /* ordinary USG */
2137 #if 0
2138 signal (SIGCHLD, sigchld);
2139 #endif
2140 #endif /* ordinary USG */
2141 #endif /* SIGCHLD */
2142 #endif /* !POSIX_SIGNALS */
2143
2144 #if !defined (DONT_REOPEN_PTY)
2145 if (pty_flag)
2146 child_setup_tty (xforkout);
2147 #endif /* not DONT_REOPEN_PTY */
2148 #ifdef WINDOWSNT
2149 pid = child_setup (xforkin, xforkout, xforkout,
2150 new_argv, 1, current_dir);
2151 #else /* not WINDOWSNT */
2152 #ifdef FD_CLOEXEC
2153 emacs_close (wait_child_setup[0]);
2154 #endif
2155 child_setup (xforkin, xforkout, xforkout,
2156 new_argv, 1, current_dir);
2157 #endif /* not WINDOWSNT */
2158 }
2159 environ = save_environ;
2160 }
2161
2162 UNBLOCK_INPUT;
2163
2164 /* This runs in the Emacs process. */
2165 if (pid < 0)
2166 {
2167 if (forkin >= 0)
2168 emacs_close (forkin);
2169 if (forkin != forkout && forkout >= 0)
2170 emacs_close (forkout);
2171 }
2172 else
2173 {
2174 /* vfork succeeded. */
2175 XPROCESS (process)->pid = pid;
2176
2177 #ifdef WINDOWSNT
2178 register_child (pid, inchannel);
2179 #endif /* WINDOWSNT */
2180
2181 /* If the subfork execv fails, and it exits,
2182 this close hangs. I don't know why.
2183 So have an interrupt jar it loose. */
2184 {
2185 struct atimer *timer;
2186 EMACS_TIME offset;
2187
2188 stop_polling ();
2189 EMACS_SET_SECS_USECS (offset, 1, 0);
2190 timer = start_atimer (ATIMER_RELATIVE, offset, create_process_1, 0);
2191
2192 if (forkin >= 0)
2193 emacs_close (forkin);
2194
2195 cancel_atimer (timer);
2196 start_polling ();
2197 }
2198
2199 if (forkin != forkout && forkout >= 0)
2200 emacs_close (forkout);
2201
2202 #ifdef HAVE_PTYS
2203 if (pty_flag)
2204 XPROCESS (process)->tty_name = build_string (pty_name);
2205 else
2206 #endif
2207 XPROCESS (process)->tty_name = Qnil;
2208
2209 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
2210 /* Wait for child_setup to complete in case that vfork is
2211 actually defined as fork. The descriptor wait_child_setup[1]
2212 of a pipe is closed at the child side either by close-on-exec
2213 on successful execvp or the _exit call in child_setup. */
2214 {
2215 char dummy;
2216
2217 emacs_close (wait_child_setup[1]);
2218 emacs_read (wait_child_setup[0], &dummy, 1);
2219 emacs_close (wait_child_setup[0]);
2220 }
2221 #endif
2222 }
2223
2224 /* Restore the signal state whether vfork succeeded or not.
2225 (We will signal an error, below, if it failed.) */
2226 #ifdef POSIX_SIGNALS
2227 #ifdef HAVE_WORKING_VFORK
2228 /* Restore the parent's signal handlers. */
2229 sigaction (SIGINT, &sigint_action, 0);
2230 sigaction (SIGQUIT, &sigquit_action, 0);
2231 #ifdef AIX
2232 sigaction (SIGHUP, &sighup_action, 0);
2233 #endif
2234 #endif /* HAVE_WORKING_VFORK */
2235 /* Stop blocking signals in the parent. */
2236 sigprocmask (SIG_SETMASK, &procmask, 0);
2237 #else /* !POSIX_SIGNALS */
2238 #ifdef SIGCHLD
2239 #if defined (BSD_SYSTEM) || defined (HPUX)
2240 sigsetmask (SIGEMPTYMASK);
2241 #else /* ordinary USG */
2242 #if 0
2243 signal (SIGCHLD, sigchld);
2244 /* Now really handle any of these signals
2245 that came in during this function. */
2246 if (sigchld_deferred)
2247 kill (getpid (), SIGCHLD);
2248 #endif
2249 #endif /* ordinary USG */
2250 #endif /* SIGCHLD */
2251 #endif /* !POSIX_SIGNALS */
2252
2253 /* Now generate the error if vfork failed. */
2254 if (pid < 0)
2255 report_file_error ("Doing vfork", Qnil);
2256 }
2257
2258 \f
2259 #ifdef HAVE_SOCKETS
2260
2261 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2262 The address family of sa is not included in the result. */
2263
2264 static Lisp_Object
2265 conv_sockaddr_to_lisp (sa, len)
2266 struct sockaddr *sa;
2267 int len;
2268 {
2269 Lisp_Object address;
2270 int i;
2271 unsigned char *cp;
2272 register struct Lisp_Vector *p;
2273
2274 switch (sa->sa_family)
2275 {
2276 case AF_INET:
2277 {
2278 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2279 len = sizeof (sin->sin_addr) + 1;
2280 address = Fmake_vector (make_number (len), Qnil);
2281 p = XVECTOR (address);
2282 p->contents[--len] = make_number (ntohs (sin->sin_port));
2283 cp = (unsigned char *)&sin->sin_addr;
2284 break;
2285 }
2286 #ifdef AF_INET6
2287 case AF_INET6:
2288 {
2289 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2290 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2291 len = sizeof (sin6->sin6_addr)/2 + 1;
2292 address = Fmake_vector (make_number (len), Qnil);
2293 p = XVECTOR (address);
2294 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2295 for (i = 0; i < len; i++)
2296 p->contents[i] = make_number (ntohs (ip6[i]));
2297 return address;
2298 }
2299 #endif
2300 #ifdef HAVE_LOCAL_SOCKETS
2301 case AF_LOCAL:
2302 {
2303 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2304 for (i = 0; i < sizeof (sockun->sun_path); i++)
2305 if (sockun->sun_path[i] == 0)
2306 break;
2307 return make_unibyte_string (sockun->sun_path, i);
2308 }
2309 #endif
2310 default:
2311 len -= sizeof (sa->sa_family);
2312 address = Fcons (make_number (sa->sa_family),
2313 Fmake_vector (make_number (len), Qnil));
2314 p = XVECTOR (XCDR (address));
2315 cp = (unsigned char *) sa + sizeof (sa->sa_family);
2316 break;
2317 }
2318
2319 i = 0;
2320 while (i < len)
2321 p->contents[i++] = make_number (*cp++);
2322
2323 return address;
2324 }
2325
2326
2327 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2328
2329 static int
2330 get_lisp_to_sockaddr_size (address, familyp)
2331 Lisp_Object address;
2332 int *familyp;
2333 {
2334 register struct Lisp_Vector *p;
2335
2336 if (VECTORP (address))
2337 {
2338 p = XVECTOR (address);
2339 if (p->size == 5)
2340 {
2341 *familyp = AF_INET;
2342 return sizeof (struct sockaddr_in);
2343 }
2344 #ifdef AF_INET6
2345 else if (p->size == 9)
2346 {
2347 *familyp = AF_INET6;
2348 return sizeof (struct sockaddr_in6);
2349 }
2350 #endif
2351 }
2352 #ifdef HAVE_LOCAL_SOCKETS
2353 else if (STRINGP (address))
2354 {
2355 *familyp = AF_LOCAL;
2356 return sizeof (struct sockaddr_un);
2357 }
2358 #endif
2359 else if (CONSP (address) && INTEGERP (XCAR (address)) && VECTORP (XCDR (address)))
2360 {
2361 struct sockaddr *sa;
2362 *familyp = XINT (XCAR (address));
2363 p = XVECTOR (XCDR (address));
2364 return p->size + sizeof (sa->sa_family);
2365 }
2366 return 0;
2367 }
2368
2369 /* Convert an address object (vector or string) to an internal sockaddr.
2370
2371 The address format has been basically validated by
2372 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2373 it could have come from user data. So if FAMILY is not valid,
2374 we return after zeroing *SA. */
2375
2376 static void
2377 conv_lisp_to_sockaddr (family, address, sa, len)
2378 int family;
2379 Lisp_Object address;
2380 struct sockaddr *sa;
2381 int len;
2382 {
2383 register struct Lisp_Vector *p;
2384 register unsigned char *cp = NULL;
2385 register int i;
2386
2387 bzero (sa, len);
2388
2389 if (VECTORP (address))
2390 {
2391 p = XVECTOR (address);
2392 if (family == AF_INET)
2393 {
2394 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2395 len = sizeof (sin->sin_addr) + 1;
2396 i = XINT (p->contents[--len]);
2397 sin->sin_port = htons (i);
2398 cp = (unsigned char *)&sin->sin_addr;
2399 sa->sa_family = family;
2400 }
2401 #ifdef AF_INET6
2402 else if (family == AF_INET6)
2403 {
2404 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2405 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2406 len = sizeof (sin6->sin6_addr) + 1;
2407 i = XINT (p->contents[--len]);
2408 sin6->sin6_port = htons (i);
2409 for (i = 0; i < len; i++)
2410 if (INTEGERP (p->contents[i]))
2411 {
2412 int j = XFASTINT (p->contents[i]) & 0xffff;
2413 ip6[i] = ntohs (j);
2414 }
2415 sa->sa_family = family;
2416 }
2417 #endif
2418 return;
2419 }
2420 else if (STRINGP (address))
2421 {
2422 #ifdef HAVE_LOCAL_SOCKETS
2423 if (family == AF_LOCAL)
2424 {
2425 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2426 cp = SDATA (address);
2427 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2428 sockun->sun_path[i] = *cp++;
2429 sa->sa_family = family;
2430 }
2431 #endif
2432 return;
2433 }
2434 else
2435 {
2436 p = XVECTOR (XCDR (address));
2437 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2438 }
2439
2440 for (i = 0; i < len; i++)
2441 if (INTEGERP (p->contents[i]))
2442 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2443 }
2444
2445 #ifdef DATAGRAM_SOCKETS
2446 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2447 1, 1, 0,
2448 doc: /* Get the current datagram address associated with PROCESS. */)
2449 (process)
2450 Lisp_Object process;
2451 {
2452 int channel;
2453
2454 CHECK_PROCESS (process);
2455
2456 if (!DATAGRAM_CONN_P (process))
2457 return Qnil;
2458
2459 channel = XPROCESS (process)->infd;
2460 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2461 datagram_address[channel].len);
2462 }
2463
2464 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2465 2, 2, 0,
2466 doc: /* Set the datagram address for PROCESS to ADDRESS.
2467 Returns nil upon error setting address, ADDRESS otherwise. */)
2468 (process, address)
2469 Lisp_Object process, address;
2470 {
2471 int channel;
2472 int family, len;
2473
2474 CHECK_PROCESS (process);
2475
2476 if (!DATAGRAM_CONN_P (process))
2477 return Qnil;
2478
2479 channel = XPROCESS (process)->infd;
2480
2481 len = get_lisp_to_sockaddr_size (address, &family);
2482 if (datagram_address[channel].len != len)
2483 return Qnil;
2484 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2485 return address;
2486 }
2487 #endif
2488 \f
2489
2490 static struct socket_options {
2491 /* The name of this option. Should be lowercase version of option
2492 name without SO_ prefix. */
2493 char *name;
2494 /* Option level SOL_... */
2495 int optlevel;
2496 /* Option number SO_... */
2497 int optnum;
2498 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2499 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2500 } socket_options[] =
2501 {
2502 #ifdef SO_BINDTODEVICE
2503 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2504 #endif
2505 #ifdef SO_BROADCAST
2506 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2507 #endif
2508 #ifdef SO_DONTROUTE
2509 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2510 #endif
2511 #ifdef SO_KEEPALIVE
2512 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2513 #endif
2514 #ifdef SO_LINGER
2515 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2516 #endif
2517 #ifdef SO_OOBINLINE
2518 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2519 #endif
2520 #ifdef SO_PRIORITY
2521 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2522 #endif
2523 #ifdef SO_REUSEADDR
2524 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2525 #endif
2526 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2527 };
2528
2529 /* Set option OPT to value VAL on socket S.
2530
2531 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2532 Signals an error if setting a known option fails.
2533 */
2534
2535 static int
2536 set_socket_option (s, opt, val)
2537 int s;
2538 Lisp_Object opt, val;
2539 {
2540 char *name;
2541 struct socket_options *sopt;
2542 int ret = 0;
2543
2544 CHECK_SYMBOL (opt);
2545
2546 name = (char *) SDATA (SYMBOL_NAME (opt));
2547 for (sopt = socket_options; sopt->name; sopt++)
2548 if (strcmp (name, sopt->name) == 0)
2549 break;
2550
2551 switch (sopt->opttype)
2552 {
2553 case SOPT_BOOL:
2554 {
2555 int optval;
2556 optval = NILP (val) ? 0 : 1;
2557 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2558 &optval, sizeof (optval));
2559 break;
2560 }
2561
2562 case SOPT_INT:
2563 {
2564 int optval;
2565 if (INTEGERP (val))
2566 optval = XINT (val);
2567 else
2568 error ("Bad option value for %s", name);
2569 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2570 &optval, sizeof (optval));
2571 break;
2572 }
2573
2574 #ifdef SO_BINDTODEVICE
2575 case SOPT_IFNAME:
2576 {
2577 char devname[IFNAMSIZ+1];
2578
2579 /* This is broken, at least in the Linux 2.4 kernel.
2580 To unbind, the arg must be a zero integer, not the empty string.
2581 This should work on all systems. KFS. 2003-09-23. */
2582 bzero (devname, sizeof devname);
2583 if (STRINGP (val))
2584 {
2585 char *arg = (char *) SDATA (val);
2586 int len = min (strlen (arg), IFNAMSIZ);
2587 bcopy (arg, devname, len);
2588 }
2589 else if (!NILP (val))
2590 error ("Bad option value for %s", name);
2591 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2592 devname, IFNAMSIZ);
2593 break;
2594 }
2595 #endif
2596
2597 #ifdef SO_LINGER
2598 case SOPT_LINGER:
2599 {
2600 struct linger linger;
2601
2602 linger.l_onoff = 1;
2603 linger.l_linger = 0;
2604 if (INTEGERP (val))
2605 linger.l_linger = XINT (val);
2606 else
2607 linger.l_onoff = NILP (val) ? 0 : 1;
2608 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2609 &linger, sizeof (linger));
2610 break;
2611 }
2612 #endif
2613
2614 default:
2615 return 0;
2616 }
2617
2618 if (ret < 0)
2619 report_file_error ("Cannot set network option",
2620 Fcons (opt, Fcons (val, Qnil)));
2621 return (1 << sopt->optbit);
2622 }
2623
2624
2625 DEFUN ("set-network-process-option",
2626 Fset_network_process_option, Sset_network_process_option,
2627 3, 4, 0,
2628 doc: /* For network process PROCESS set option OPTION to value VALUE.
2629 See `make-network-process' for a list of options and values.
2630 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2631 OPTION is not a supported option, return nil instead; otherwise return t. */)
2632 (process, option, value, no_error)
2633 Lisp_Object process, option, value;
2634 Lisp_Object no_error;
2635 {
2636 int s;
2637 struct Lisp_Process *p;
2638
2639 CHECK_PROCESS (process);
2640 p = XPROCESS (process);
2641 if (!NETCONN1_P (p))
2642 error ("Process is not a network process");
2643
2644 s = p->infd;
2645 if (s < 0)
2646 error ("Process is not running");
2647
2648 if (set_socket_option (s, option, value))
2649 {
2650 p->childp = Fplist_put (p->childp, option, value);
2651 return Qt;
2652 }
2653
2654 if (NILP (no_error))
2655 error ("Unknown or unsupported option");
2656
2657 return Qnil;
2658 }
2659
2660 \f
2661 #ifdef HAVE_SERIAL
2662 DEFUN ("serial-process-configure",
2663 Fserial_process_configure,
2664 Sserial_process_configure,
2665 0, MANY, 0,
2666 doc: /* Configure speed, bytesize, etc. of a serial process.
2667
2668 Arguments are specified as keyword/argument pairs. Attributes that
2669 are not given are re-initialized from the process's current
2670 configuration (available via the function `process-contact') or set to
2671 reasonable default values. The following arguments are defined:
2672
2673 :process PROCESS
2674 :name NAME
2675 :buffer BUFFER
2676 :port PORT
2677 -- Any of these arguments can be given to identify the process that is
2678 to be configured. If none of these arguments is given, the current
2679 buffer's process is used.
2680
2681 :speed SPEED -- SPEED is the speed of the serial port in bits per
2682 second, also called baud rate. Any value can be given for SPEED, but
2683 most serial ports work only at a few defined values between 1200 and
2684 115200, with 9600 being the most common value. If SPEED is nil, the
2685 serial port is not configured any further, i.e., all other arguments
2686 are ignored. This may be useful for special serial ports such as
2687 Bluetooth-to-serial converters which can only be configured through AT
2688 commands. A value of nil for SPEED can be used only when passed
2689 through `make-serial-process' or `serial-term'.
2690
2691 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2692 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2693
2694 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2695 `odd' (use odd parity), or the symbol `even' (use even parity). If
2696 PARITY is not given, no parity is used.
2697
2698 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2699 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2700 is not given or nil, 1 stopbit is used.
2701
2702 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2703 flowcontrol to be used, which is either nil (don't use flowcontrol),
2704 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2705 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2706 flowcontrol is used.
2707
2708 `serial-process-configure' is called by `make-serial-process' for the
2709 initial configuration of the serial port.
2710
2711 Examples:
2712
2713 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2714
2715 \(serial-process-configure
2716 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2717
2718 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2719
2720 usage: (serial-process-configure &rest ARGS) */)
2721 (nargs, args)
2722 int nargs;
2723 Lisp_Object *args;
2724 {
2725 struct Lisp_Process *p;
2726 Lisp_Object contact = Qnil;
2727 Lisp_Object proc = Qnil;
2728 struct gcpro gcpro1;
2729
2730 contact = Flist (nargs, args);
2731 GCPRO1 (contact);
2732
2733 proc = Fplist_get (contact, QCprocess);
2734 if (NILP (proc))
2735 proc = Fplist_get (contact, QCname);
2736 if (NILP (proc))
2737 proc = Fplist_get (contact, QCbuffer);
2738 if (NILP (proc))
2739 proc = Fplist_get (contact, QCport);
2740 proc = get_process (proc);
2741 p = XPROCESS (proc);
2742 if (!EQ (p->type, Qserial))
2743 error ("Not a serial process");
2744
2745 if (NILP (Fplist_get (p->childp, QCspeed)))
2746 {
2747 UNGCPRO;
2748 return Qnil;
2749 }
2750
2751 serial_configure (p, contact);
2752
2753 UNGCPRO;
2754 return Qnil;
2755 }
2756
2757 /* Used by make-serial-process to recover from errors. */
2758 Lisp_Object make_serial_process_unwind (Lisp_Object proc)
2759 {
2760 if (!PROCESSP (proc))
2761 abort ();
2762 remove_process (proc);
2763 return Qnil;
2764 }
2765
2766 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2767 0, MANY, 0,
2768 doc: /* Create and return a serial port process.
2769
2770 In Emacs, serial port connections are represented by process objects,
2771 so input and output work as for subprocesses, and `delete-process'
2772 closes a serial port connection. However, a serial process has no
2773 process id, it cannot be signaled, and the status codes are different
2774 from normal processes.
2775
2776 `make-serial-process' creates a process and a buffer, on which you
2777 probably want to use `process-send-string'. Try \\[serial-term] for
2778 an interactive terminal. See below for examples.
2779
2780 Arguments are specified as keyword/argument pairs. The following
2781 arguments are defined:
2782
2783 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2784 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2785 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2786 the backslashes in strings).
2787
2788 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2789 which is called by `make-serial-process'.
2790
2791 :name NAME -- NAME is the name of the process. If NAME is not given,
2792 the value of PORT is used.
2793
2794 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2795 with the process. Process output goes at the end of that buffer,
2796 unless you specify an output stream or filter function to handle the
2797 output. If BUFFER is not given, the value of NAME is used.
2798
2799 :coding CODING -- If CODING is a symbol, it specifies the coding
2800 system used for both reading and writing for this process. If CODING
2801 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2802 ENCODING is used for writing.
2803
2804 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2805 the process is running. If BOOL is not given, query before exiting.
2806
2807 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2808 In the stopped state, a serial process does not accept incoming data,
2809 but you can send outgoing data. The stopped state is cleared by
2810 `continue-process' and set by `stop-process'.
2811
2812 :filter FILTER -- Install FILTER as the process filter.
2813
2814 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2815
2816 :plist PLIST -- Install PLIST as the initial plist of the process.
2817
2818 :speed
2819 :bytesize
2820 :parity
2821 :stopbits
2822 :flowcontrol
2823 -- These arguments are handled by `serial-process-configure', which is
2824 called by `make-serial-process'.
2825
2826 The original argument list, possibly modified by later configuration,
2827 is available via the function `process-contact'.
2828
2829 Examples:
2830
2831 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2832
2833 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2834
2835 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2836
2837 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2838
2839 usage: (make-serial-process &rest ARGS) */)
2840 (nargs, args)
2841 int nargs;
2842 Lisp_Object *args;
2843 {
2844 int fd = -1;
2845 Lisp_Object proc, contact, port;
2846 struct Lisp_Process *p;
2847 struct gcpro gcpro1;
2848 Lisp_Object name, buffer;
2849 Lisp_Object tem, val;
2850 int specpdl_count = -1;
2851
2852 if (nargs == 0)
2853 return Qnil;
2854
2855 contact = Flist (nargs, args);
2856 GCPRO1 (contact);
2857
2858 port = Fplist_get (contact, QCport);
2859 if (NILP (port))
2860 error ("No port specified");
2861 CHECK_STRING (port);
2862
2863 if (NILP (Fplist_member (contact, QCspeed)))
2864 error (":speed not specified");
2865 if (!NILP (Fplist_get (contact, QCspeed)))
2866 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2867
2868 name = Fplist_get (contact, QCname);
2869 if (NILP (name))
2870 name = port;
2871 CHECK_STRING (name);
2872 proc = make_process (name);
2873 specpdl_count = SPECPDL_INDEX ();
2874 record_unwind_protect (make_serial_process_unwind, proc);
2875 p = XPROCESS (proc);
2876
2877 fd = serial_open ((char*) SDATA (port));
2878 p->infd = fd;
2879 p->outfd = fd;
2880 if (fd > max_process_desc)
2881 max_process_desc = fd;
2882 chan_process[fd] = proc;
2883
2884 buffer = Fplist_get (contact, QCbuffer);
2885 if (NILP (buffer))
2886 buffer = name;
2887 buffer = Fget_buffer_create (buffer);
2888 p->buffer = buffer;
2889
2890 p->childp = contact;
2891 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
2892 p->type = Qserial;
2893 p->sentinel = Fplist_get (contact, QCsentinel);
2894 p->filter = Fplist_get (contact, QCfilter);
2895 p->log = Qnil;
2896 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2897 p->kill_without_query = 1;
2898 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2899 p->command = Qt;
2900 p->pty_flag = 0;
2901
2902 if (!EQ (p->command, Qt))
2903 {
2904 FD_SET (fd, &input_wait_mask);
2905 FD_SET (fd, &non_keyboard_wait_mask);
2906 }
2907
2908 if (BUFFERP (buffer))
2909 {
2910 set_marker_both (p->mark, buffer,
2911 BUF_ZV (XBUFFER (buffer)),
2912 BUF_ZV_BYTE (XBUFFER (buffer)));
2913 }
2914
2915 tem = Fplist_member (contact, QCcoding);
2916 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2917 tem = Qnil;
2918
2919 val = Qnil;
2920 if (!NILP (tem))
2921 {
2922 val = XCAR (XCDR (tem));
2923 if (CONSP (val))
2924 val = XCAR (val);
2925 }
2926 else if (!NILP (Vcoding_system_for_read))
2927 val = Vcoding_system_for_read;
2928 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
2929 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
2930 val = Qnil;
2931 p->decode_coding_system = val;
2932
2933 val = Qnil;
2934 if (!NILP (tem))
2935 {
2936 val = XCAR (XCDR (tem));
2937 if (CONSP (val))
2938 val = XCDR (val);
2939 }
2940 else if (!NILP (Vcoding_system_for_write))
2941 val = Vcoding_system_for_write;
2942 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
2943 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
2944 val = Qnil;
2945 p->encode_coding_system = val;
2946
2947 setup_process_coding_systems (proc);
2948 p->decoding_buf = make_uninit_string (0);
2949 p->decoding_carryover = 0;
2950 p->encoding_buf = make_uninit_string (0);
2951 p->inherit_coding_system_flag
2952 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2953
2954 Fserial_process_configure(nargs, args);
2955
2956 specpdl_ptr = specpdl + specpdl_count;
2957
2958 UNGCPRO;
2959 return proc;
2960 }
2961 #endif /* HAVE_SERIAL */
2962
2963 /* Create a network stream/datagram client/server process. Treated
2964 exactly like a normal process when reading and writing. Primary
2965 differences are in status display and process deletion. A network
2966 connection has no PID; you cannot signal it. All you can do is
2967 stop/continue it and deactivate/close it via delete-process */
2968
2969 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2970 0, MANY, 0,
2971 doc: /* Create and return a network server or client process.
2972
2973 In Emacs, network connections are represented by process objects, so
2974 input and output work as for subprocesses and `delete-process' closes
2975 a network connection. However, a network process has no process id,
2976 it cannot be signaled, and the status codes are different from normal
2977 processes.
2978
2979 Arguments are specified as keyword/argument pairs. The following
2980 arguments are defined:
2981
2982 :name NAME -- NAME is name for process. It is modified if necessary
2983 to make it unique.
2984
2985 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2986 with the process. Process output goes at end of that buffer, unless
2987 you specify an output stream or filter function to handle the output.
2988 BUFFER may be also nil, meaning that this process is not associated
2989 with any buffer.
2990
2991 :host HOST -- HOST is name of the host to connect to, or its IP
2992 address. The symbol `local' specifies the local host. If specified
2993 for a server process, it must be a valid name or address for the local
2994 host, and only clients connecting to that address will be accepted.
2995
2996 :service SERVICE -- SERVICE is name of the service desired, or an
2997 integer specifying a port number to connect to. If SERVICE is t,
2998 a random port number is selected for the server. (If Emacs was
2999 compiled with getaddrinfo, a port number can also be specified as a
3000 string, e.g. "80", as well as an integer. This is not portable.)
3001
3002 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3003 stream type connection, `datagram' creates a datagram type connection.
3004
3005 :family FAMILY -- FAMILY is the address (and protocol) family for the
3006 service specified by HOST and SERVICE. The default (nil) is to use
3007 whatever address family (IPv4 or IPv6) that is defined for the host
3008 and port number specified by HOST and SERVICE. Other address families
3009 supported are:
3010 local -- for a local (i.e. UNIX) address specified by SERVICE.
3011 ipv4 -- use IPv4 address family only.
3012 ipv6 -- use IPv6 address family only.
3013
3014 :local ADDRESS -- ADDRESS is the local address used for the connection.
3015 This parameter is ignored when opening a client process. When specified
3016 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3017
3018 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3019 connection. This parameter is ignored when opening a stream server
3020 process. For a datagram server process, it specifies the initial
3021 setting of the remote datagram address. When specified for a client
3022 process, the FAMILY, HOST, and SERVICE args are ignored.
3023
3024 The format of ADDRESS depends on the address family:
3025 - An IPv4 address is represented as an vector of integers [A B C D P]
3026 corresponding to numeric IP address A.B.C.D and port number P.
3027 - A local address is represented as a string with the address in the
3028 local address space.
3029 - An "unsupported family" address is represented by a cons (F . AV)
3030 where F is the family number and AV is a vector containing the socket
3031 address data with one element per address data byte. Do not rely on
3032 this format in portable code, as it may depend on implementation
3033 defined constants, data sizes, and data structure alignment.
3034
3035 :coding CODING -- If CODING is a symbol, it specifies the coding
3036 system used for both reading and writing for this process. If CODING
3037 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3038 ENCODING is used for writing.
3039
3040 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
3041 return without waiting for the connection to complete; instead, the
3042 sentinel function will be called with second arg matching "open" (if
3043 successful) or "failed" when the connect completes. Default is to use
3044 a blocking connect (i.e. wait) for stream type connections.
3045
3046 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3047 running when Emacs is exited.
3048
3049 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3050 In the stopped state, a server process does not accept new
3051 connections, and a client process does not handle incoming traffic.
3052 The stopped state is cleared by `continue-process' and set by
3053 `stop-process'.
3054
3055 :filter FILTER -- Install FILTER as the process filter.
3056
3057 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3058 process filter are multibyte, otherwise they are unibyte.
3059 If this keyword is not specified, the strings are multibyte if
3060 `default-enable-multibyte-characters' is non-nil.
3061
3062 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3063
3064 :log LOG -- Install LOG as the server process log function. This
3065 function is called when the server accepts a network connection from a
3066 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3067 is the server process, CLIENT is the new process for the connection,
3068 and MESSAGE is a string.
3069
3070 :plist PLIST -- Install PLIST as the new process' initial plist.
3071
3072 :server QLEN -- if QLEN is non-nil, create a server process for the
3073 specified FAMILY, SERVICE, and connection type (stream or datagram).
3074 If QLEN is an integer, it is used as the max. length of the server's
3075 pending connection queue (also known as the backlog); the default
3076 queue length is 5. Default is to create a client process.
3077
3078 The following network options can be specified for this connection:
3079
3080 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3081 :dontroute BOOL -- Only send to directly connected hosts.
3082 :keepalive BOOL -- Send keep-alive messages on network stream.
3083 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3084 :oobinline BOOL -- Place out-of-band data in receive data stream.
3085 :priority INT -- Set protocol defined priority for sent packets.
3086 :reuseaddr BOOL -- Allow reusing a recently used local address
3087 (this is allowed by default for a server process).
3088 :bindtodevice NAME -- bind to interface NAME. Using this may require
3089 special privileges on some systems.
3090
3091 Consult the relevant system programmer's manual pages for more
3092 information on using these options.
3093
3094
3095 A server process will listen for and accept connections from clients.
3096 When a client connection is accepted, a new network process is created
3097 for the connection with the following parameters:
3098
3099 - The client's process name is constructed by concatenating the server
3100 process' NAME and a client identification string.
3101 - If the FILTER argument is non-nil, the client process will not get a
3102 separate process buffer; otherwise, the client's process buffer is a newly
3103 created buffer named after the server process' BUFFER name or process
3104 NAME concatenated with the client identification string.
3105 - The connection type and the process filter and sentinel parameters are
3106 inherited from the server process' TYPE, FILTER and SENTINEL.
3107 - The client process' contact info is set according to the client's
3108 addressing information (typically an IP address and a port number).
3109 - The client process' plist is initialized from the server's plist.
3110
3111 Notice that the FILTER and SENTINEL args are never used directly by
3112 the server process. Also, the BUFFER argument is not used directly by
3113 the server process, but via the optional :log function, accepted (and
3114 failed) connections may be logged in the server process' buffer.
3115
3116 The original argument list, modified with the actual connection
3117 information, is available via the `process-contact' function.
3118
3119 usage: (make-network-process &rest ARGS) */)
3120 (nargs, args)
3121 int nargs;
3122 Lisp_Object *args;
3123 {
3124 Lisp_Object proc;
3125 Lisp_Object contact;
3126 struct Lisp_Process *p;
3127 #ifdef HAVE_GETADDRINFO
3128 struct addrinfo ai, *res, *lres;
3129 struct addrinfo hints;
3130 char *portstring, portbuf[128];
3131 #else /* HAVE_GETADDRINFO */
3132 struct _emacs_addrinfo
3133 {
3134 int ai_family;
3135 int ai_socktype;
3136 int ai_protocol;
3137 int ai_addrlen;
3138 struct sockaddr *ai_addr;
3139 struct _emacs_addrinfo *ai_next;
3140 } ai, *res, *lres;
3141 #endif /* HAVE_GETADDRINFO */
3142 struct sockaddr_in address_in;
3143 #ifdef HAVE_LOCAL_SOCKETS
3144 struct sockaddr_un address_un;
3145 #endif
3146 int port;
3147 int ret = 0;
3148 int xerrno = 0;
3149 int s = -1, outch, inch;
3150 struct gcpro gcpro1;
3151 int count = SPECPDL_INDEX ();
3152 int count1;
3153 Lisp_Object QCaddress; /* one of QClocal or QCremote */
3154 Lisp_Object tem;
3155 Lisp_Object name, buffer, host, service, address;
3156 Lisp_Object filter, sentinel;
3157 int is_non_blocking_client = 0;
3158 int is_server = 0, backlog = 5;
3159 int socktype;
3160 int family = -1;
3161
3162 if (nargs == 0)
3163 return Qnil;
3164
3165 /* Save arguments for process-contact and clone-process. */
3166 contact = Flist (nargs, args);
3167 GCPRO1 (contact);
3168
3169 #ifdef WINDOWSNT
3170 /* Ensure socket support is loaded if available. */
3171 init_winsock (TRUE);
3172 #endif
3173
3174 /* :type TYPE (nil: stream, datagram */
3175 tem = Fplist_get (contact, QCtype);
3176 if (NILP (tem))
3177 socktype = SOCK_STREAM;
3178 #ifdef DATAGRAM_SOCKETS
3179 else if (EQ (tem, Qdatagram))
3180 socktype = SOCK_DGRAM;
3181 #endif
3182 else
3183 error ("Unsupported connection type");
3184
3185 /* :server BOOL */
3186 tem = Fplist_get (contact, QCserver);
3187 if (!NILP (tem))
3188 {
3189 /* Don't support network sockets when non-blocking mode is
3190 not available, since a blocked Emacs is not useful. */
3191 #if !defined(O_NONBLOCK) && !defined(O_NDELAY)
3192 error ("Network servers not supported");
3193 #else
3194 is_server = 1;
3195 if (INTEGERP (tem))
3196 backlog = XINT (tem);
3197 #endif
3198 }
3199
3200 /* Make QCaddress an alias for :local (server) or :remote (client). */
3201 QCaddress = is_server ? QClocal : QCremote;
3202
3203 /* :nowait BOOL */
3204 if (!is_server && socktype == SOCK_STREAM
3205 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3206 {
3207 #ifndef NON_BLOCKING_CONNECT
3208 error ("Non-blocking connect not supported");
3209 #else
3210 is_non_blocking_client = 1;
3211 #endif
3212 }
3213
3214 name = Fplist_get (contact, QCname);
3215 buffer = Fplist_get (contact, QCbuffer);
3216 filter = Fplist_get (contact, QCfilter);
3217 sentinel = Fplist_get (contact, QCsentinel);
3218
3219 CHECK_STRING (name);
3220
3221 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3222 ai.ai_socktype = socktype;
3223 ai.ai_protocol = 0;
3224 ai.ai_next = NULL;
3225 res = &ai;
3226
3227 /* :local ADDRESS or :remote ADDRESS */
3228 address = Fplist_get (contact, QCaddress);
3229 if (!NILP (address))
3230 {
3231 host = service = Qnil;
3232
3233 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3234 error ("Malformed :address");
3235 ai.ai_family = family;
3236 ai.ai_addr = alloca (ai.ai_addrlen);
3237 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3238 goto open_socket;
3239 }
3240
3241 /* :family FAMILY -- nil (for Inet), local, or integer. */
3242 tem = Fplist_get (contact, QCfamily);
3243 if (NILP (tem))
3244 {
3245 #if defined(HAVE_GETADDRINFO) && defined(AF_INET6)
3246 family = AF_UNSPEC;
3247 #else
3248 family = AF_INET;
3249 #endif
3250 }
3251 #ifdef HAVE_LOCAL_SOCKETS
3252 else if (EQ (tem, Qlocal))
3253 family = AF_LOCAL;
3254 #endif
3255 #ifdef AF_INET6
3256 else if (EQ (tem, Qipv6))
3257 family = AF_INET6;
3258 #endif
3259 else if (EQ (tem, Qipv4))
3260 family = AF_INET;
3261 else if (INTEGERP (tem))
3262 family = XINT (tem);
3263 else
3264 error ("Unknown address family");
3265
3266 ai.ai_family = family;
3267
3268 /* :service SERVICE -- string, integer (port number), or t (random port). */
3269 service = Fplist_get (contact, QCservice);
3270
3271 #ifdef HAVE_LOCAL_SOCKETS
3272 if (family == AF_LOCAL)
3273 {
3274 /* Host is not used. */
3275 host = Qnil;
3276 CHECK_STRING (service);
3277 bzero (&address_un, sizeof address_un);
3278 address_un.sun_family = AF_LOCAL;
3279 strncpy (address_un.sun_path, SDATA (service), sizeof address_un.sun_path);
3280 ai.ai_addr = (struct sockaddr *) &address_un;
3281 ai.ai_addrlen = sizeof address_un;
3282 goto open_socket;
3283 }
3284 #endif
3285
3286 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3287 host = Fplist_get (contact, QChost);
3288 if (!NILP (host))
3289 {
3290 if (EQ (host, Qlocal))
3291 host = build_string ("localhost");
3292 CHECK_STRING (host);
3293 }
3294
3295 /* Slow down polling to every ten seconds.
3296 Some kernels have a bug which causes retrying connect to fail
3297 after a connect. Polling can interfere with gethostbyname too. */
3298 #ifdef POLL_FOR_INPUT
3299 if (socktype == SOCK_STREAM)
3300 {
3301 record_unwind_protect (unwind_stop_other_atimers, Qnil);
3302 bind_polling_period (10);
3303 }
3304 #endif
3305
3306 #ifdef HAVE_GETADDRINFO
3307 /* If we have a host, use getaddrinfo to resolve both host and service.
3308 Otherwise, use getservbyname to lookup the service. */
3309 if (!NILP (host))
3310 {
3311
3312 /* SERVICE can either be a string or int.
3313 Convert to a C string for later use by getaddrinfo. */
3314 if (EQ (service, Qt))
3315 portstring = "0";
3316 else if (INTEGERP (service))
3317 {
3318 sprintf (portbuf, "%ld", (long) XINT (service));
3319 portstring = portbuf;
3320 }
3321 else
3322 {
3323 CHECK_STRING (service);
3324 portstring = SDATA (service);
3325 }
3326
3327 immediate_quit = 1;
3328 QUIT;
3329 memset (&hints, 0, sizeof (hints));
3330 hints.ai_flags = 0;
3331 hints.ai_family = family;
3332 hints.ai_socktype = socktype;
3333 hints.ai_protocol = 0;
3334
3335 #ifdef HAVE_RES_INIT
3336 res_init ();
3337 #endif
3338
3339 ret = getaddrinfo (SDATA (host), portstring, &hints, &res);
3340 if (ret)
3341 #ifdef HAVE_GAI_STRERROR
3342 error ("%s/%s %s", SDATA (host), portstring, gai_strerror(ret));
3343 #else
3344 error ("%s/%s getaddrinfo error %d", SDATA (host), portstring, ret);
3345 #endif
3346 immediate_quit = 0;
3347
3348 goto open_socket;
3349 }
3350 #endif /* HAVE_GETADDRINFO */
3351
3352 /* We end up here if getaddrinfo is not defined, or in case no hostname
3353 has been specified (e.g. for a local server process). */
3354
3355 if (EQ (service, Qt))
3356 port = 0;
3357 else if (INTEGERP (service))
3358 port = htons ((unsigned short) XINT (service));
3359 else
3360 {
3361 struct servent *svc_info;
3362 CHECK_STRING (service);
3363 svc_info = getservbyname (SDATA (service),
3364 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3365 if (svc_info == 0)
3366 error ("Unknown service: %s", SDATA (service));
3367 port = svc_info->s_port;
3368 }
3369
3370 bzero (&address_in, sizeof address_in);
3371 address_in.sin_family = family;
3372 address_in.sin_addr.s_addr = INADDR_ANY;
3373 address_in.sin_port = port;
3374
3375 #ifndef HAVE_GETADDRINFO
3376 if (!NILP (host))
3377 {
3378 struct hostent *host_info_ptr;
3379
3380 /* gethostbyname may fail with TRY_AGAIN, but we don't honour that,
3381 as it may `hang' Emacs for a very long time. */
3382 immediate_quit = 1;
3383 QUIT;
3384
3385 #ifdef HAVE_RES_INIT
3386 res_init ();
3387 #endif
3388
3389 host_info_ptr = gethostbyname (SDATA (host));
3390 immediate_quit = 0;
3391
3392 if (host_info_ptr)
3393 {
3394 bcopy (host_info_ptr->h_addr, (char *) &address_in.sin_addr,
3395 host_info_ptr->h_length);
3396 family = host_info_ptr->h_addrtype;
3397 address_in.sin_family = family;
3398 }
3399 else
3400 /* Attempt to interpret host as numeric inet address */
3401 {
3402 unsigned long numeric_addr;
3403 numeric_addr = inet_addr ((char *) SDATA (host));
3404 if (numeric_addr == -1)
3405 error ("Unknown host \"%s\"", SDATA (host));
3406
3407 bcopy ((char *)&numeric_addr, (char *) &address_in.sin_addr,
3408 sizeof (address_in.sin_addr));
3409 }
3410
3411 }
3412 #endif /* not HAVE_GETADDRINFO */
3413
3414 ai.ai_family = family;
3415 ai.ai_addr = (struct sockaddr *) &address_in;
3416 ai.ai_addrlen = sizeof address_in;
3417
3418 open_socket:
3419
3420 /* Do this in case we never enter the for-loop below. */
3421 count1 = SPECPDL_INDEX ();
3422 s = -1;
3423
3424 for (lres = res; lres; lres = lres->ai_next)
3425 {
3426 int optn, optbits;
3427
3428 retry_connect:
3429
3430 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
3431 if (s < 0)
3432 {
3433 xerrno = errno;
3434 continue;
3435 }
3436
3437 #ifdef DATAGRAM_SOCKETS
3438 if (!is_server && socktype == SOCK_DGRAM)
3439 break;
3440 #endif /* DATAGRAM_SOCKETS */
3441
3442 #ifdef NON_BLOCKING_CONNECT
3443 if (is_non_blocking_client)
3444 {
3445 #ifdef O_NONBLOCK
3446 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3447 #else
3448 ret = fcntl (s, F_SETFL, O_NDELAY);
3449 #endif
3450 if (ret < 0)
3451 {
3452 xerrno = errno;
3453 emacs_close (s);
3454 s = -1;
3455 continue;
3456 }
3457 }
3458 #endif
3459
3460 /* Make us close S if quit. */
3461 record_unwind_protect (close_file_unwind, make_number (s));
3462
3463 /* Parse network options in the arg list.
3464 We simply ignore anything which isn't a known option (including other keywords).
3465 An error is signaled if setting a known option fails. */
3466 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3467 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3468
3469 if (is_server)
3470 {
3471 /* Configure as a server socket. */
3472
3473 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3474 explicit :reuseaddr key to override this. */
3475 #ifdef HAVE_LOCAL_SOCKETS
3476 if (family != AF_LOCAL)
3477 #endif
3478 if (!(optbits & (1 << OPIX_REUSEADDR)))
3479 {
3480 int optval = 1;
3481 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3482 report_file_error ("Cannot set reuse option on server socket", Qnil);
3483 }
3484
3485 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3486 report_file_error ("Cannot bind server socket", Qnil);
3487
3488 #ifdef HAVE_GETSOCKNAME
3489 if (EQ (service, Qt))
3490 {
3491 struct sockaddr_in sa1;
3492 int len1 = sizeof (sa1);
3493 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3494 {
3495 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3496 service = make_number (ntohs (sa1.sin_port));
3497 contact = Fplist_put (contact, QCservice, service);
3498 }
3499 }
3500 #endif
3501
3502 if (socktype == SOCK_STREAM && listen (s, backlog))
3503 report_file_error ("Cannot listen on server socket", Qnil);
3504
3505 break;
3506 }
3507
3508 immediate_quit = 1;
3509 QUIT;
3510
3511 /* This turns off all alarm-based interrupts; the
3512 bind_polling_period call above doesn't always turn all the
3513 short-interval ones off, especially if interrupt_input is
3514 set.
3515
3516 It'd be nice to be able to control the connect timeout
3517 though. Would non-blocking connect calls be portable?
3518
3519 This used to be conditioned by HAVE_GETADDRINFO. Why? */
3520
3521 turn_on_atimers (0);
3522
3523 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3524 xerrno = errno;
3525
3526 turn_on_atimers (1);
3527
3528 if (ret == 0 || xerrno == EISCONN)
3529 {
3530 /* The unwind-protect will be discarded afterwards.
3531 Likewise for immediate_quit. */
3532 break;
3533 }
3534
3535 #ifdef NON_BLOCKING_CONNECT
3536 #ifdef EINPROGRESS
3537 if (is_non_blocking_client && xerrno == EINPROGRESS)
3538 break;
3539 #else
3540 #ifdef EWOULDBLOCK
3541 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3542 break;
3543 #endif
3544 #endif
3545 #endif
3546
3547 immediate_quit = 0;
3548
3549 /* Discard the unwind protect closing S. */
3550 specpdl_ptr = specpdl + count1;
3551 emacs_close (s);
3552 s = -1;
3553
3554 if (xerrno == EINTR)
3555 goto retry_connect;
3556 }
3557
3558 if (s >= 0)
3559 {
3560 #ifdef DATAGRAM_SOCKETS
3561 if (socktype == SOCK_DGRAM)
3562 {
3563 if (datagram_address[s].sa)
3564 abort ();
3565 datagram_address[s].sa = (struct sockaddr *) xmalloc (lres->ai_addrlen);
3566 datagram_address[s].len = lres->ai_addrlen;
3567 if (is_server)
3568 {
3569 Lisp_Object remote;
3570 bzero (datagram_address[s].sa, lres->ai_addrlen);
3571 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3572 {
3573 int rfamily, rlen;
3574 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3575 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
3576 conv_lisp_to_sockaddr (rfamily, remote,
3577 datagram_address[s].sa, rlen);
3578 }
3579 }
3580 else
3581 bcopy (lres->ai_addr, datagram_address[s].sa, lres->ai_addrlen);
3582 }
3583 #endif
3584 contact = Fplist_put (contact, QCaddress,
3585 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3586 #ifdef HAVE_GETSOCKNAME
3587 if (!is_server)
3588 {
3589 struct sockaddr_in sa1;
3590 int len1 = sizeof (sa1);
3591 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3592 contact = Fplist_put (contact, QClocal,
3593 conv_sockaddr_to_lisp (&sa1, len1));
3594 }
3595 #endif
3596 }
3597
3598 immediate_quit = 0;
3599
3600 #ifdef HAVE_GETADDRINFO
3601 if (res != &ai)
3602 {
3603 BLOCK_INPUT;
3604 freeaddrinfo (res);
3605 UNBLOCK_INPUT;
3606 }
3607 #endif
3608
3609 /* Discard the unwind protect for closing S, if any. */
3610 specpdl_ptr = specpdl + count1;
3611
3612 /* Unwind bind_polling_period and request_sigio. */
3613 unbind_to (count, Qnil);
3614
3615 if (s < 0)
3616 {
3617 /* If non-blocking got this far - and failed - assume non-blocking is
3618 not supported after all. This is probably a wrong assumption, but
3619 the normal blocking calls to open-network-stream handles this error
3620 better. */
3621 if (is_non_blocking_client)
3622 return Qnil;
3623
3624 errno = xerrno;
3625 if (is_server)
3626 report_file_error ("make server process failed", contact);
3627 else
3628 report_file_error ("make client process failed", contact);
3629 }
3630
3631 inch = s;
3632 outch = s;
3633
3634 if (!NILP (buffer))
3635 buffer = Fget_buffer_create (buffer);
3636 proc = make_process (name);
3637
3638 chan_process[inch] = proc;
3639
3640 #ifdef O_NONBLOCK
3641 fcntl (inch, F_SETFL, O_NONBLOCK);
3642 #else
3643 #ifdef O_NDELAY
3644 fcntl (inch, F_SETFL, O_NDELAY);
3645 #endif
3646 #endif
3647
3648 p = XPROCESS (proc);
3649
3650 p->childp = contact;
3651 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
3652 p->type = Qnetwork;
3653
3654 p->buffer = buffer;
3655 p->sentinel = sentinel;
3656 p->filter = filter;
3657 p->log = Fplist_get (contact, QClog);
3658 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3659 p->kill_without_query = 1;
3660 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3661 p->command = Qt;
3662 p->pid = 0;
3663 p->infd = inch;
3664 p->outfd = outch;
3665 if (is_server && socktype == SOCK_STREAM)
3666 p->status = Qlisten;
3667
3668 /* Make the process marker point into the process buffer (if any). */
3669 if (BUFFERP (buffer))
3670 set_marker_both (p->mark, buffer,
3671 BUF_ZV (XBUFFER (buffer)),
3672 BUF_ZV_BYTE (XBUFFER (buffer)));
3673
3674 #ifdef NON_BLOCKING_CONNECT
3675 if (is_non_blocking_client)
3676 {
3677 /* We may get here if connect did succeed immediately. However,
3678 in that case, we still need to signal this like a non-blocking
3679 connection. */
3680 p->status = Qconnect;
3681 if (!FD_ISSET (inch, &connect_wait_mask))
3682 {
3683 FD_SET (inch, &connect_wait_mask);
3684 num_pending_connects++;
3685 }
3686 }
3687 else
3688 #endif
3689 /* A server may have a client filter setting of Qt, but it must
3690 still listen for incoming connects unless it is stopped. */
3691 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3692 || (EQ (p->status, Qlisten) && NILP (p->command)))
3693 {
3694 FD_SET (inch, &input_wait_mask);
3695 FD_SET (inch, &non_keyboard_wait_mask);
3696 }
3697
3698 if (inch > max_process_desc)
3699 max_process_desc = inch;
3700
3701 tem = Fplist_member (contact, QCcoding);
3702 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3703 tem = Qnil; /* No error message (too late!). */
3704
3705 {
3706 /* Setup coding systems for communicating with the network stream. */
3707 struct gcpro gcpro1;
3708 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3709 Lisp_Object coding_systems = Qt;
3710 Lisp_Object args[5], val;
3711
3712 if (!NILP (tem))
3713 {
3714 val = XCAR (XCDR (tem));
3715 if (CONSP (val))
3716 val = XCAR (val);
3717 }
3718 else if (!NILP (Vcoding_system_for_read))
3719 val = Vcoding_system_for_read;
3720 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3721 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
3722 /* We dare not decode end-of-line format by setting VAL to
3723 Qraw_text, because the existing Emacs Lisp libraries
3724 assume that they receive bare code including a sequene of
3725 CR LF. */
3726 val = Qnil;
3727 else
3728 {
3729 if (NILP (host) || NILP (service))
3730 coding_systems = Qnil;
3731 else
3732 {
3733 args[0] = Qopen_network_stream, args[1] = name,
3734 args[2] = buffer, args[3] = host, args[4] = service;
3735 GCPRO1 (proc);
3736 coding_systems = Ffind_operation_coding_system (5, args);
3737 UNGCPRO;
3738 }
3739 if (CONSP (coding_systems))
3740 val = XCAR (coding_systems);
3741 else if (CONSP (Vdefault_process_coding_system))
3742 val = XCAR (Vdefault_process_coding_system);
3743 else
3744 val = Qnil;
3745 }
3746 p->decode_coding_system = val;
3747
3748 if (!NILP (tem))
3749 {
3750 val = XCAR (XCDR (tem));
3751 if (CONSP (val))
3752 val = XCDR (val);
3753 }
3754 else if (!NILP (Vcoding_system_for_write))
3755 val = Vcoding_system_for_write;
3756 else if (NILP (current_buffer->enable_multibyte_characters))
3757 val = Qnil;
3758 else
3759 {
3760 if (EQ (coding_systems, Qt))
3761 {
3762 if (NILP (host) || NILP (service))
3763 coding_systems = Qnil;
3764 else
3765 {
3766 args[0] = Qopen_network_stream, args[1] = name,
3767 args[2] = buffer, args[3] = host, args[4] = service;
3768 GCPRO1 (proc);
3769 coding_systems = Ffind_operation_coding_system (5, args);
3770 UNGCPRO;
3771 }
3772 }
3773 if (CONSP (coding_systems))
3774 val = XCDR (coding_systems);
3775 else if (CONSP (Vdefault_process_coding_system))
3776 val = XCDR (Vdefault_process_coding_system);
3777 else
3778 val = Qnil;
3779 }
3780 p->encode_coding_system = val;
3781 }
3782 setup_process_coding_systems (proc);
3783
3784 p->decoding_buf = make_uninit_string (0);
3785 p->decoding_carryover = 0;
3786 p->encoding_buf = make_uninit_string (0);
3787
3788 p->inherit_coding_system_flag
3789 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3790
3791 UNGCPRO;
3792 return proc;
3793 }
3794 #endif /* HAVE_SOCKETS */
3795
3796 \f
3797 #if defined(HAVE_SOCKETS) && defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
3798
3799 #ifdef SIOCGIFCONF
3800 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3801 doc: /* Return an alist of all network interfaces and their network address.
3802 Each element is a cons, the car of which is a string containing the
3803 interface name, and the cdr is the network address in internal
3804 format; see the description of ADDRESS in `make-network-process'. */)
3805 ()
3806 {
3807 struct ifconf ifconf;
3808 struct ifreq *ifreqs = NULL;
3809 int ifaces = 0;
3810 int buf_size, s;
3811 Lisp_Object res;
3812
3813 s = socket (AF_INET, SOCK_STREAM, 0);
3814 if (s < 0)
3815 return Qnil;
3816
3817 again:
3818 ifaces += 25;
3819 buf_size = ifaces * sizeof(ifreqs[0]);
3820 ifreqs = (struct ifreq *)xrealloc(ifreqs, buf_size);
3821 if (!ifreqs)
3822 {
3823 close (s);
3824 return Qnil;
3825 }
3826
3827 ifconf.ifc_len = buf_size;
3828 ifconf.ifc_req = ifreqs;
3829 if (ioctl (s, SIOCGIFCONF, &ifconf))
3830 {
3831 close (s);
3832 return Qnil;
3833 }
3834
3835 if (ifconf.ifc_len == buf_size)
3836 goto again;
3837
3838 close (s);
3839 ifaces = ifconf.ifc_len / sizeof (ifreqs[0]);
3840
3841 res = Qnil;
3842 while (--ifaces >= 0)
3843 {
3844 struct ifreq *ifq = &ifreqs[ifaces];
3845 char namebuf[sizeof (ifq->ifr_name) + 1];
3846 if (ifq->ifr_addr.sa_family != AF_INET)
3847 continue;
3848 bcopy (ifq->ifr_name, namebuf, sizeof (ifq->ifr_name));
3849 namebuf[sizeof (ifq->ifr_name)] = 0;
3850 res = Fcons (Fcons (build_string (namebuf),
3851 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3852 sizeof (struct sockaddr))),
3853 res);
3854 }
3855
3856 return res;
3857 }
3858 #endif /* SIOCGIFCONF */
3859
3860 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
3861
3862 struct ifflag_def {
3863 int flag_bit;
3864 char *flag_sym;
3865 };
3866
3867 static struct ifflag_def ifflag_table[] = {
3868 #ifdef IFF_UP
3869 { IFF_UP, "up" },
3870 #endif
3871 #ifdef IFF_BROADCAST
3872 { IFF_BROADCAST, "broadcast" },
3873 #endif
3874 #ifdef IFF_DEBUG
3875 { IFF_DEBUG, "debug" },
3876 #endif
3877 #ifdef IFF_LOOPBACK
3878 { IFF_LOOPBACK, "loopback" },
3879 #endif
3880 #ifdef IFF_POINTOPOINT
3881 { IFF_POINTOPOINT, "pointopoint" },
3882 #endif
3883 #ifdef IFF_RUNNING
3884 { IFF_RUNNING, "running" },
3885 #endif
3886 #ifdef IFF_NOARP
3887 { IFF_NOARP, "noarp" },
3888 #endif
3889 #ifdef IFF_PROMISC
3890 { IFF_PROMISC, "promisc" },
3891 #endif
3892 #ifdef IFF_NOTRAILERS
3893 { IFF_NOTRAILERS, "notrailers" },
3894 #endif
3895 #ifdef IFF_ALLMULTI
3896 { IFF_ALLMULTI, "allmulti" },
3897 #endif
3898 #ifdef IFF_MASTER
3899 { IFF_MASTER, "master" },
3900 #endif
3901 #ifdef IFF_SLAVE
3902 { IFF_SLAVE, "slave" },
3903 #endif
3904 #ifdef IFF_MULTICAST
3905 { IFF_MULTICAST, "multicast" },
3906 #endif
3907 #ifdef IFF_PORTSEL
3908 { IFF_PORTSEL, "portsel" },
3909 #endif
3910 #ifdef IFF_AUTOMEDIA
3911 { IFF_AUTOMEDIA, "automedia" },
3912 #endif
3913 #ifdef IFF_DYNAMIC
3914 { IFF_DYNAMIC, "dynamic" },
3915 #endif
3916 #ifdef IFF_OACTIVE
3917 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3918 #endif
3919 #ifdef IFF_SIMPLEX
3920 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3921 #endif
3922 #ifdef IFF_LINK0
3923 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3924 #endif
3925 #ifdef IFF_LINK1
3926 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3927 #endif
3928 #ifdef IFF_LINK2
3929 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3930 #endif
3931 { 0, 0 }
3932 };
3933
3934 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
3935 doc: /* Return information about network interface named IFNAME.
3936 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3937 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3938 NETMASK is the layer 3 network mask, HWADDR is the layer 2 addres, and
3939 FLAGS is the current flags of the interface. */)
3940 (ifname)
3941 Lisp_Object ifname;
3942 {
3943 struct ifreq rq;
3944 Lisp_Object res = Qnil;
3945 Lisp_Object elt;
3946 int s;
3947 int any = 0;
3948
3949 CHECK_STRING (ifname);
3950
3951 bzero (rq.ifr_name, sizeof rq.ifr_name);
3952 strncpy (rq.ifr_name, SDATA (ifname), sizeof (rq.ifr_name));
3953
3954 s = socket (AF_INET, SOCK_STREAM, 0);
3955 if (s < 0)
3956 return Qnil;
3957
3958 elt = Qnil;
3959 #if defined(SIOCGIFFLAGS) && defined(HAVE_STRUCT_IFREQ_IFR_FLAGS)
3960 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3961 {
3962 int flags = rq.ifr_flags;
3963 struct ifflag_def *fp;
3964 int fnum;
3965
3966 any++;
3967 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3968 {
3969 if (flags & fp->flag_bit)
3970 {
3971 elt = Fcons (intern (fp->flag_sym), elt);
3972 flags -= fp->flag_bit;
3973 }
3974 }
3975 for (fnum = 0; flags && fnum < 32; fnum++)
3976 {
3977 if (flags & (1 << fnum))
3978 {
3979 elt = Fcons (make_number (fnum), elt);
3980 }
3981 }
3982 }
3983 #endif
3984 res = Fcons (elt, res);
3985
3986 elt = Qnil;
3987 #if defined(SIOCGIFHWADDR) && defined(HAVE_STRUCT_IFREQ_IFR_HWADDR)
3988 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3989 {
3990 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3991 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3992 int n;
3993
3994 any++;
3995 for (n = 0; n < 6; n++)
3996 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
3997 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3998 }
3999 #endif
4000 res = Fcons (elt, res);
4001
4002 elt = Qnil;
4003 #if defined(SIOCGIFNETMASK) && (defined(HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined(HAVE_STRUCT_IFREQ_IFR_ADDR))
4004 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4005 {
4006 any++;
4007 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4008 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4009 #else
4010 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4011 #endif
4012 }
4013 #endif
4014 res = Fcons (elt, res);
4015
4016 elt = Qnil;
4017 #if defined(SIOCGIFBRDADDR) && defined(HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4018 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4019 {
4020 any++;
4021 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4022 }
4023 #endif
4024 res = Fcons (elt, res);
4025
4026 elt = Qnil;
4027 #if defined(SIOCGIFADDR) && defined(HAVE_STRUCT_IFREQ_IFR_ADDR)
4028 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4029 {
4030 any++;
4031 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4032 }
4033 #endif
4034 res = Fcons (elt, res);
4035
4036 close (s);
4037
4038 return any ? res : Qnil;
4039 }
4040 #endif
4041 #endif /* HAVE_SOCKETS */
4042
4043 /* Turn off input and output for process PROC. */
4044
4045 void
4046 deactivate_process (proc)
4047 Lisp_Object proc;
4048 {
4049 register int inchannel, outchannel;
4050 register struct Lisp_Process *p = XPROCESS (proc);
4051
4052 inchannel = p->infd;
4053 outchannel = p->outfd;
4054
4055 #ifdef ADAPTIVE_READ_BUFFERING
4056 if (p->read_output_delay > 0)
4057 {
4058 if (--process_output_delay_count < 0)
4059 process_output_delay_count = 0;
4060 p->read_output_delay = 0;
4061 p->read_output_skip = 0;
4062 }
4063 #endif
4064
4065 if (inchannel >= 0)
4066 {
4067 /* Beware SIGCHLD hereabouts. */
4068 flush_pending_output (inchannel);
4069 emacs_close (inchannel);
4070 if (outchannel >= 0 && outchannel != inchannel)
4071 emacs_close (outchannel);
4072
4073 p->infd = -1;
4074 p->outfd = -1;
4075 #ifdef DATAGRAM_SOCKETS
4076 if (DATAGRAM_CHAN_P (inchannel))
4077 {
4078 xfree (datagram_address[inchannel].sa);
4079 datagram_address[inchannel].sa = 0;
4080 datagram_address[inchannel].len = 0;
4081 }
4082 #endif
4083 chan_process[inchannel] = Qnil;
4084 FD_CLR (inchannel, &input_wait_mask);
4085 FD_CLR (inchannel, &non_keyboard_wait_mask);
4086 #ifdef NON_BLOCKING_CONNECT
4087 if (FD_ISSET (inchannel, &connect_wait_mask))
4088 {
4089 FD_CLR (inchannel, &connect_wait_mask);
4090 if (--num_pending_connects < 0)
4091 abort ();
4092 }
4093 #endif
4094 if (inchannel == max_process_desc)
4095 {
4096 int i;
4097 /* We just closed the highest-numbered process input descriptor,
4098 so recompute the highest-numbered one now. */
4099 max_process_desc = 0;
4100 for (i = 0; i < MAXDESC; i++)
4101 if (!NILP (chan_process[i]))
4102 max_process_desc = i;
4103 }
4104 }
4105 }
4106
4107 /* Close all descriptors currently in use for communication
4108 with subprocess. This is used in a newly-forked subprocess
4109 to get rid of irrelevant descriptors. */
4110
4111 void
4112 close_process_descs ()
4113 {
4114 #ifndef WINDOWSNT
4115 int i;
4116 for (i = 0; i < MAXDESC; i++)
4117 {
4118 Lisp_Object process;
4119 process = chan_process[i];
4120 if (!NILP (process))
4121 {
4122 int in = XPROCESS (process)->infd;
4123 int out = XPROCESS (process)->outfd;
4124 if (in >= 0)
4125 emacs_close (in);
4126 if (out >= 0 && in != out)
4127 emacs_close (out);
4128 }
4129 }
4130 #endif
4131 }
4132 \f
4133 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4134 0, 4, 0,
4135 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4136 It is read into the process' buffers or given to their filter functions.
4137 Non-nil arg PROCESS means do not return until some output has been received
4138 from PROCESS.
4139
4140 Non-nil second arg SECONDS and third arg MILLISEC are number of
4141 seconds and milliseconds to wait; return after that much time whether
4142 or not there is input. If SECONDS is a floating point number,
4143 it specifies a fractional number of seconds to wait.
4144 The MILLISEC argument is obsolete and should be avoided.
4145
4146 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
4147 from PROCESS, suspending reading output from other processes.
4148 If JUST-THIS-ONE is an integer, don't run any timers either.
4149 Return non-nil if we received any output before the timeout expired. */)
4150 (process, seconds, millisec, just_this_one)
4151 register Lisp_Object process, seconds, millisec, just_this_one;
4152 {
4153 int secs, usecs = 0;
4154
4155 if (! NILP (process))
4156 CHECK_PROCESS (process);
4157 else
4158 just_this_one = Qnil;
4159
4160 if (!NILP (millisec))
4161 { /* Obsolete calling convention using integers rather than floats. */
4162 CHECK_NUMBER (millisec);
4163 if (NILP (seconds))
4164 seconds = make_float (XINT (millisec) / 1000.0);
4165 else
4166 {
4167 CHECK_NUMBER (seconds);
4168 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4169 }
4170 }
4171
4172 if (!NILP (seconds))
4173 {
4174 if (INTEGERP (seconds))
4175 secs = XINT (seconds);
4176 else if (FLOATP (seconds))
4177 {
4178 double timeout = XFLOAT_DATA (seconds);
4179 secs = (int) timeout;
4180 usecs = (int) ((timeout - (double) secs) * 1000000);
4181 }
4182 else
4183 wrong_type_argument (Qnumberp, seconds);
4184
4185 if (secs < 0 || (secs == 0 && usecs == 0))
4186 secs = -1, usecs = 0;
4187 }
4188 else
4189 secs = NILP (process) ? -1 : 0;
4190
4191 return
4192 (wait_reading_process_output (secs, usecs, 0, 0,
4193 Qnil,
4194 !NILP (process) ? XPROCESS (process) : NULL,
4195 NILP (just_this_one) ? 0 :
4196 !INTEGERP (just_this_one) ? 1 : -1)
4197 ? Qt : Qnil);
4198 }
4199
4200 /* Accept a connection for server process SERVER on CHANNEL. */
4201
4202 static int connect_counter = 0;
4203
4204 static void
4205 server_accept_connection (server, channel)
4206 Lisp_Object server;
4207 int channel;
4208 {
4209 Lisp_Object proc, caller, name, buffer;
4210 Lisp_Object contact, host, service;
4211 struct Lisp_Process *ps= XPROCESS (server);
4212 struct Lisp_Process *p;
4213 int s;
4214 union u_sockaddr {
4215 struct sockaddr sa;
4216 struct sockaddr_in in;
4217 #ifdef AF_INET6
4218 struct sockaddr_in6 in6;
4219 #endif
4220 #ifdef HAVE_LOCAL_SOCKETS
4221 struct sockaddr_un un;
4222 #endif
4223 } saddr;
4224 int len = sizeof saddr;
4225
4226 s = accept (channel, &saddr.sa, &len);
4227
4228 if (s < 0)
4229 {
4230 int code = errno;
4231
4232 if (code == EAGAIN)
4233 return;
4234 #ifdef EWOULDBLOCK
4235 if (code == EWOULDBLOCK)
4236 return;
4237 #endif
4238
4239 if (!NILP (ps->log))
4240 call3 (ps->log, server, Qnil,
4241 concat3 (build_string ("accept failed with code"),
4242 Fnumber_to_string (make_number (code)),
4243 build_string ("\n")));
4244 return;
4245 }
4246
4247 connect_counter++;
4248
4249 /* Setup a new process to handle the connection. */
4250
4251 /* Generate a unique identification of the caller, and build contact
4252 information for this process. */
4253 host = Qt;
4254 service = Qnil;
4255 switch (saddr.sa.sa_family)
4256 {
4257 case AF_INET:
4258 {
4259 Lisp_Object args[5];
4260 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4261 args[0] = build_string ("%d.%d.%d.%d");
4262 args[1] = make_number (*ip++);
4263 args[2] = make_number (*ip++);
4264 args[3] = make_number (*ip++);
4265 args[4] = make_number (*ip++);
4266 host = Fformat (5, args);
4267 service = make_number (ntohs (saddr.in.sin_port));
4268
4269 args[0] = build_string (" <%s:%d>");
4270 args[1] = host;
4271 args[2] = service;
4272 caller = Fformat (3, args);
4273 }
4274 break;
4275
4276 #ifdef AF_INET6
4277 case AF_INET6:
4278 {
4279 Lisp_Object args[9];
4280 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4281 int i;
4282 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4283 for (i = 0; i < 8; i++)
4284 args[i+1] = make_number (ntohs(ip6[i]));
4285 host = Fformat (9, args);
4286 service = make_number (ntohs (saddr.in.sin_port));
4287
4288 args[0] = build_string (" <[%s]:%d>");
4289 args[1] = host;
4290 args[2] = service;
4291 caller = Fformat (3, args);
4292 }
4293 break;
4294 #endif
4295
4296 #ifdef HAVE_LOCAL_SOCKETS
4297 case AF_LOCAL:
4298 #endif
4299 default:
4300 caller = Fnumber_to_string (make_number (connect_counter));
4301 caller = concat3 (build_string (" <"), caller, build_string (">"));
4302 break;
4303 }
4304
4305 /* Create a new buffer name for this process if it doesn't have a
4306 filter. The new buffer name is based on the buffer name or
4307 process name of the server process concatenated with the caller
4308 identification. */
4309
4310 if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
4311 buffer = Qnil;
4312 else
4313 {
4314 buffer = ps->buffer;
4315 if (!NILP (buffer))
4316 buffer = Fbuffer_name (buffer);
4317 else
4318 buffer = ps->name;
4319 if (!NILP (buffer))
4320 {
4321 buffer = concat2 (buffer, caller);
4322 buffer = Fget_buffer_create (buffer);
4323 }
4324 }
4325
4326 /* Generate a unique name for the new server process. Combine the
4327 server process name with the caller identification. */
4328
4329 name = concat2 (ps->name, caller);
4330 proc = make_process (name);
4331
4332 chan_process[s] = proc;
4333
4334 #ifdef O_NONBLOCK
4335 fcntl (s, F_SETFL, O_NONBLOCK);
4336 #else
4337 #ifdef O_NDELAY
4338 fcntl (s, F_SETFL, O_NDELAY);
4339 #endif
4340 #endif
4341
4342 p = XPROCESS (proc);
4343
4344 /* Build new contact information for this setup. */
4345 contact = Fcopy_sequence (ps->childp);
4346 contact = Fplist_put (contact, QCserver, Qnil);
4347 contact = Fplist_put (contact, QChost, host);
4348 if (!NILP (service))
4349 contact = Fplist_put (contact, QCservice, service);
4350 contact = Fplist_put (contact, QCremote,
4351 conv_sockaddr_to_lisp (&saddr.sa, len));
4352 #ifdef HAVE_GETSOCKNAME
4353 len = sizeof saddr;
4354 if (getsockname (s, &saddr.sa, &len) == 0)
4355 contact = Fplist_put (contact, QClocal,
4356 conv_sockaddr_to_lisp (&saddr.sa, len));
4357 #endif
4358
4359 p->childp = contact;
4360 p->plist = Fcopy_sequence (ps->plist);
4361 p->type = Qnetwork;
4362
4363 p->buffer = buffer;
4364 p->sentinel = ps->sentinel;
4365 p->filter = ps->filter;
4366 p->command = Qnil;
4367 p->pid = 0;
4368 p->infd = s;
4369 p->outfd = s;
4370 p->status = Qrun;
4371
4372 /* Client processes for accepted connections are not stopped initially. */
4373 if (!EQ (p->filter, Qt))
4374 {
4375 FD_SET (s, &input_wait_mask);
4376 FD_SET (s, &non_keyboard_wait_mask);
4377 }
4378
4379 if (s > max_process_desc)
4380 max_process_desc = s;
4381
4382 /* Setup coding system for new process based on server process.
4383 This seems to be the proper thing to do, as the coding system
4384 of the new process should reflect the settings at the time the
4385 server socket was opened; not the current settings. */
4386
4387 p->decode_coding_system = ps->decode_coding_system;
4388 p->encode_coding_system = ps->encode_coding_system;
4389 setup_process_coding_systems (proc);
4390
4391 p->decoding_buf = make_uninit_string (0);
4392 p->decoding_carryover = 0;
4393 p->encoding_buf = make_uninit_string (0);
4394
4395 p->inherit_coding_system_flag
4396 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4397
4398 if (!NILP (ps->log))
4399 call3 (ps->log, server, proc,
4400 concat3 (build_string ("accept from "),
4401 (STRINGP (host) ? host : build_string ("-")),
4402 build_string ("\n")));
4403
4404 if (!NILP (p->sentinel))
4405 exec_sentinel (proc,
4406 concat3 (build_string ("open from "),
4407 (STRINGP (host) ? host : build_string ("-")),
4408 build_string ("\n")));
4409 }
4410
4411 /* This variable is different from waiting_for_input in keyboard.c.
4412 It is used to communicate to a lisp process-filter/sentinel (via the
4413 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4414 for user-input when that process-filter was called.
4415 waiting_for_input cannot be used as that is by definition 0 when
4416 lisp code is being evalled.
4417 This is also used in record_asynch_buffer_change.
4418 For that purpose, this must be 0
4419 when not inside wait_reading_process_output. */
4420 static int waiting_for_user_input_p;
4421
4422 static Lisp_Object
4423 wait_reading_process_output_unwind (data)
4424 Lisp_Object data;
4425 {
4426 waiting_for_user_input_p = XINT (data);
4427 return Qnil;
4428 }
4429
4430 /* This is here so breakpoints can be put on it. */
4431 static void
4432 wait_reading_process_output_1 ()
4433 {
4434 }
4435
4436 /* Use a wrapper around select to work around a bug in gdb 5.3.
4437 Normally, the wrapper is optimzed away by inlining.
4438
4439 If emacs is stopped inside select, the gdb backtrace doesn't
4440 show the function which called select, so it is practically
4441 impossible to step through wait_reading_process_output. */
4442
4443 #ifndef select
4444 static INLINE int
4445 select_wrapper (n, rfd, wfd, xfd, tmo)
4446 int n;
4447 SELECT_TYPE *rfd, *wfd, *xfd;
4448 EMACS_TIME *tmo;
4449 {
4450 return select (n, rfd, wfd, xfd, tmo);
4451 }
4452 #define select select_wrapper
4453 #endif
4454
4455 /* Read and dispose of subprocess output while waiting for timeout to
4456 elapse and/or keyboard input to be available.
4457
4458 TIME_LIMIT is:
4459 timeout in seconds, or
4460 zero for no limit, or
4461 -1 means gobble data immediately available but don't wait for any.
4462
4463 MICROSECS is:
4464 an additional duration to wait, measured in microseconds.
4465 If this is nonzero and time_limit is 0, then the timeout
4466 consists of MICROSECS only.
4467
4468 READ_KBD is a lisp value:
4469 0 to ignore keyboard input, or
4470 1 to return when input is available, or
4471 -1 meaning caller will actually read the input, so don't throw to
4472 the quit handler, or
4473
4474 DO_DISPLAY != 0 means redisplay should be done to show subprocess
4475 output that arrives.
4476
4477 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4478 (and gobble terminal input into the buffer if any arrives).
4479
4480 If WAIT_PROC is specified, wait until something arrives from that
4481 process. The return value is true if we read some input from
4482 that process.
4483
4484 If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
4485 (suspending output from other processes). A negative value
4486 means don't run any timers either.
4487
4488 If WAIT_PROC is specified, then the function returns true if we
4489 received input from that process before the timeout elapsed.
4490 Otherwise, return true if we received input from any process. */
4491
4492 int
4493 wait_reading_process_output (time_limit, microsecs, read_kbd, do_display,
4494 wait_for_cell, wait_proc, just_wait_proc)
4495 int time_limit, microsecs, read_kbd, do_display;
4496 Lisp_Object wait_for_cell;
4497 struct Lisp_Process *wait_proc;
4498 int just_wait_proc;
4499 {
4500 register int channel, nfds;
4501 SELECT_TYPE Available;
4502 #ifdef NON_BLOCKING_CONNECT
4503 SELECT_TYPE Connecting;
4504 int check_connect;
4505 #endif
4506 int check_delay, no_avail;
4507 int xerrno;
4508 Lisp_Object proc;
4509 EMACS_TIME timeout, end_time;
4510 int wait_channel = -1;
4511 int got_some_input = 0;
4512 int count = SPECPDL_INDEX ();
4513
4514 FD_ZERO (&Available);
4515 #ifdef NON_BLOCKING_CONNECT
4516 FD_ZERO (&Connecting);
4517 #endif
4518
4519 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4520 if (wait_proc != NULL)
4521 wait_channel = wait_proc->infd;
4522
4523 record_unwind_protect (wait_reading_process_output_unwind,
4524 make_number (waiting_for_user_input_p));
4525 waiting_for_user_input_p = read_kbd;
4526
4527 /* Since we may need to wait several times,
4528 compute the absolute time to return at. */
4529 if (time_limit || microsecs)
4530 {
4531 EMACS_GET_TIME (end_time);
4532 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
4533 EMACS_ADD_TIME (end_time, end_time, timeout);
4534 }
4535
4536 while (1)
4537 {
4538 int timeout_reduced_for_timers = 0;
4539
4540 /* If calling from keyboard input, do not quit
4541 since we want to return C-g as an input character.
4542 Otherwise, do pending quit if requested. */
4543 if (read_kbd >= 0)
4544 QUIT;
4545 #ifdef SYNC_INPUT
4546 else
4547 {
4548 if (interrupt_input_pending)
4549 handle_async_input ();
4550 if (pending_atimers)
4551 do_pending_atimers ();
4552 }
4553 #endif
4554
4555 /* Exit now if the cell we're waiting for became non-nil. */
4556 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4557 break;
4558
4559 /* Compute time from now till when time limit is up */
4560 /* Exit if already run out */
4561 if (time_limit == -1)
4562 {
4563 /* -1 specified for timeout means
4564 gobble output available now
4565 but don't wait at all. */
4566
4567 EMACS_SET_SECS_USECS (timeout, 0, 0);
4568 }
4569 else if (time_limit || microsecs)
4570 {
4571 EMACS_GET_TIME (timeout);
4572 EMACS_SUB_TIME (timeout, end_time, timeout);
4573 if (EMACS_TIME_NEG_P (timeout))
4574 break;
4575 }
4576 else
4577 {
4578 EMACS_SET_SECS_USECS (timeout, 100000, 0);
4579 }
4580
4581 /* Normally we run timers here.
4582 But not if wait_for_cell; in those cases,
4583 the wait is supposed to be short,
4584 and those callers cannot handle running arbitrary Lisp code here. */
4585 if (NILP (wait_for_cell)
4586 && just_wait_proc >= 0)
4587 {
4588 EMACS_TIME timer_delay;
4589
4590 do
4591 {
4592 int old_timers_run = timers_run;
4593 struct buffer *old_buffer = current_buffer;
4594 Lisp_Object old_window = selected_window;
4595
4596 timer_delay = timer_check (1);
4597
4598 /* If a timer has run, this might have changed buffers
4599 an alike. Make read_key_sequence aware of that. */
4600 if (timers_run != old_timers_run
4601 && (old_buffer != current_buffer
4602 || !EQ (old_window, selected_window))
4603 && waiting_for_user_input_p == -1)
4604 record_asynch_buffer_change ();
4605
4606 if (timers_run != old_timers_run && do_display)
4607 /* We must retry, since a timer may have requeued itself
4608 and that could alter the time_delay. */
4609 redisplay_preserve_echo_area (9);
4610 else
4611 break;
4612 }
4613 while (!detect_input_pending ());
4614
4615 /* If there is unread keyboard input, also return. */
4616 if (read_kbd != 0
4617 && requeued_events_pending_p ())
4618 break;
4619
4620 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
4621 {
4622 EMACS_TIME difference;
4623 EMACS_SUB_TIME (difference, timer_delay, timeout);
4624 if (EMACS_TIME_NEG_P (difference))
4625 {
4626 timeout = timer_delay;
4627 timeout_reduced_for_timers = 1;
4628 }
4629 }
4630 /* If time_limit is -1, we are not going to wait at all. */
4631 else if (time_limit != -1)
4632 {
4633 /* This is so a breakpoint can be put here. */
4634 wait_reading_process_output_1 ();
4635 }
4636 }
4637
4638 /* Cause C-g and alarm signals to take immediate action,
4639 and cause input available signals to zero out timeout.
4640
4641 It is important that we do this before checking for process
4642 activity. If we get a SIGCHLD after the explicit checks for
4643 process activity, timeout is the only way we will know. */
4644 if (read_kbd < 0)
4645 set_waiting_for_input (&timeout);
4646
4647 /* If status of something has changed, and no input is
4648 available, notify the user of the change right away. After
4649 this explicit check, we'll let the SIGCHLD handler zap
4650 timeout to get our attention. When Emacs is run
4651 interactively, only do this with a nonzero DO_DISPLAY
4652 argument, because status_notify triggers redisplay. */
4653 if (update_tick != process_tick
4654 && (do_display || noninteractive))
4655 {
4656 SELECT_TYPE Atemp;
4657 #ifdef NON_BLOCKING_CONNECT
4658 SELECT_TYPE Ctemp;
4659 #endif
4660
4661 Atemp = input_wait_mask;
4662 IF_NON_BLOCKING_CONNECT (Ctemp = connect_wait_mask);
4663
4664 EMACS_SET_SECS_USECS (timeout, 0, 0);
4665 if ((select (max (max (max_process_desc, max_keyboard_desc),
4666 max_gpm_desc) + 1,
4667 &Atemp,
4668 #ifdef NON_BLOCKING_CONNECT
4669 (num_pending_connects > 0 ? &Ctemp : (SELECT_TYPE *)0),
4670 #else
4671 (SELECT_TYPE *)0,
4672 #endif
4673 (SELECT_TYPE *)0, &timeout)
4674 <= 0))
4675 {
4676 /* It's okay for us to do this and then continue with
4677 the loop, since timeout has already been zeroed out. */
4678 clear_waiting_for_input ();
4679 status_notify (NULL);
4680 }
4681 }
4682
4683 /* Don't wait for output from a non-running process. Just
4684 read whatever data has already been received. */
4685 if (wait_proc && wait_proc->raw_status_new)
4686 update_status (wait_proc);
4687 if (wait_proc
4688 && ! EQ (wait_proc->status, Qrun)
4689 && ! EQ (wait_proc->status, Qconnect))
4690 {
4691 int nread, total_nread = 0;
4692
4693 clear_waiting_for_input ();
4694 XSETPROCESS (proc, wait_proc);
4695
4696 /* Read data from the process, until we exhaust it. */
4697 while (wait_proc->infd >= 0)
4698 {
4699 nread = read_process_output (proc, wait_proc->infd);
4700
4701 if (nread == 0)
4702 break;
4703
4704 if (0 < nread)
4705 {
4706 total_nread += nread;
4707 got_some_input = 1;
4708 }
4709 #ifdef EIO
4710 else if (nread == -1 && EIO == errno)
4711 break;
4712 #endif
4713 #ifdef EAGAIN
4714 else if (nread == -1 && EAGAIN == errno)
4715 break;
4716 #endif
4717 #ifdef EWOULDBLOCK
4718 else if (nread == -1 && EWOULDBLOCK == errno)
4719 break;
4720 #endif
4721 }
4722 if (total_nread > 0 && do_display)
4723 redisplay_preserve_echo_area (10);
4724
4725 break;
4726 }
4727
4728 /* Wait till there is something to do */
4729
4730 if (wait_proc && just_wait_proc)
4731 {
4732 if (wait_proc->infd < 0) /* Terminated */
4733 break;
4734 FD_SET (wait_proc->infd, &Available);
4735 check_delay = 0;
4736 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4737 }
4738 else if (!NILP (wait_for_cell))
4739 {
4740 Available = non_process_wait_mask;
4741 check_delay = 0;
4742 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4743 }
4744 else
4745 {
4746 if (! read_kbd)
4747 Available = non_keyboard_wait_mask;
4748 else
4749 Available = input_wait_mask;
4750 IF_NON_BLOCKING_CONNECT (check_connect = (num_pending_connects > 0));
4751 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4752 }
4753
4754 /* If frame size has changed or the window is newly mapped,
4755 redisplay now, before we start to wait. There is a race
4756 condition here; if a SIGIO arrives between now and the select
4757 and indicates that a frame is trashed, the select may block
4758 displaying a trashed screen. */
4759 if (frame_garbaged && do_display)
4760 {
4761 clear_waiting_for_input ();
4762 redisplay_preserve_echo_area (11);
4763 if (read_kbd < 0)
4764 set_waiting_for_input (&timeout);
4765 }
4766
4767 no_avail = 0;
4768 if (read_kbd && detect_input_pending ())
4769 {
4770 nfds = 0;
4771 no_avail = 1;
4772 }
4773 else
4774 {
4775 #ifdef NON_BLOCKING_CONNECT
4776 if (check_connect)
4777 Connecting = connect_wait_mask;
4778 #endif
4779
4780 #ifdef ADAPTIVE_READ_BUFFERING
4781 /* Set the timeout for adaptive read buffering if any
4782 process has non-zero read_output_skip and non-zero
4783 read_output_delay, and we are not reading output for a
4784 specific wait_channel. It is not executed if
4785 Vprocess_adaptive_read_buffering is nil. */
4786 if (process_output_skip && check_delay > 0)
4787 {
4788 int usecs = EMACS_USECS (timeout);
4789 if (EMACS_SECS (timeout) > 0 || usecs > READ_OUTPUT_DELAY_MAX)
4790 usecs = READ_OUTPUT_DELAY_MAX;
4791 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4792 {
4793 proc = chan_process[channel];
4794 if (NILP (proc))
4795 continue;
4796 /* Find minimum non-zero read_output_delay among the
4797 processes with non-zero read_output_skip. */
4798 if (XPROCESS (proc)->read_output_delay > 0)
4799 {
4800 check_delay--;
4801 if (!XPROCESS (proc)->read_output_skip)
4802 continue;
4803 FD_CLR (channel, &Available);
4804 XPROCESS (proc)->read_output_skip = 0;
4805 if (XPROCESS (proc)->read_output_delay < usecs)
4806 usecs = XPROCESS (proc)->read_output_delay;
4807 }
4808 }
4809 EMACS_SET_SECS_USECS (timeout, 0, usecs);
4810 process_output_skip = 0;
4811 }
4812 #endif
4813 #ifdef HAVE_NS
4814 nfds = ns_select
4815 #else
4816 nfds = select
4817 #endif
4818 (max (max (max_process_desc, max_keyboard_desc),
4819 max_gpm_desc) + 1,
4820 &Available,
4821 #ifdef NON_BLOCKING_CONNECT
4822 (check_connect ? &Connecting : (SELECT_TYPE *)0),
4823 #else
4824 (SELECT_TYPE *)0,
4825 #endif
4826 (SELECT_TYPE *)0, &timeout);
4827 }
4828
4829 xerrno = errno;
4830
4831 /* Make C-g and alarm signals set flags again */
4832 clear_waiting_for_input ();
4833
4834 /* If we woke up due to SIGWINCH, actually change size now. */
4835 do_pending_window_change (0);
4836
4837 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
4838 /* We wanted the full specified time, so return now. */
4839 break;
4840 if (nfds < 0)
4841 {
4842 if (xerrno == EINTR)
4843 no_avail = 1;
4844 else if (xerrno == EBADF)
4845 {
4846 #ifdef AIX
4847 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4848 the child's closure of the pts gives the parent a SIGHUP, and
4849 the ptc file descriptor is automatically closed,
4850 yielding EBADF here or at select() call above.
4851 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4852 in m/ibmrt-aix.h), and here we just ignore the select error.
4853 Cleanup occurs c/o status_notify after SIGCLD. */
4854 no_avail = 1; /* Cannot depend on values returned */
4855 #else
4856 abort ();
4857 #endif
4858 }
4859 else
4860 error ("select error: %s", emacs_strerror (xerrno));
4861 }
4862
4863 if (no_avail)
4864 {
4865 FD_ZERO (&Available);
4866 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4867 }
4868
4869 #if 0 /* When polling is used, interrupt_input is 0,
4870 so get_input_pending should read the input.
4871 So this should not be needed. */
4872 /* If we are using polling for input,
4873 and we see input available, make it get read now.
4874 Otherwise it might not actually get read for a second.
4875 And on hpux, since we turn off polling in wait_reading_process_output,
4876 it might never get read at all if we don't spend much time
4877 outside of wait_reading_process_output. */
4878 if (read_kbd && interrupt_input
4879 && keyboard_bit_set (&Available)
4880 && input_polling_used ())
4881 kill (getpid (), SIGALRM);
4882 #endif
4883
4884 /* Check for keyboard input */
4885 /* If there is any, return immediately
4886 to give it higher priority than subprocesses */
4887
4888 if (read_kbd != 0)
4889 {
4890 int old_timers_run = timers_run;
4891 struct buffer *old_buffer = current_buffer;
4892 Lisp_Object old_window = selected_window;
4893 int leave = 0;
4894
4895 if (detect_input_pending_run_timers (do_display))
4896 {
4897 swallow_events (do_display);
4898 if (detect_input_pending_run_timers (do_display))
4899 leave = 1;
4900 }
4901
4902 /* If a timer has run, this might have changed buffers
4903 an alike. Make read_key_sequence aware of that. */
4904 if (timers_run != old_timers_run
4905 && waiting_for_user_input_p == -1
4906 && (old_buffer != current_buffer
4907 || !EQ (old_window, selected_window)))
4908 record_asynch_buffer_change ();
4909
4910 if (leave)
4911 break;
4912 }
4913
4914 /* If there is unread keyboard input, also return. */
4915 if (read_kbd != 0
4916 && requeued_events_pending_p ())
4917 break;
4918
4919 /* If we are not checking for keyboard input now,
4920 do process events (but don't run any timers).
4921 This is so that X events will be processed.
4922 Otherwise they may have to wait until polling takes place.
4923 That would causes delays in pasting selections, for example.
4924
4925 (We used to do this only if wait_for_cell.) */
4926 if (read_kbd == 0 && detect_input_pending ())
4927 {
4928 swallow_events (do_display);
4929 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4930 if (detect_input_pending ())
4931 break;
4932 #endif
4933 }
4934
4935 /* Exit now if the cell we're waiting for became non-nil. */
4936 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4937 break;
4938
4939 #ifdef SIGIO
4940 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4941 go read it. This can happen with X on BSD after logging out.
4942 In that case, there really is no input and no SIGIO,
4943 but select says there is input. */
4944
4945 if (read_kbd && interrupt_input
4946 && keyboard_bit_set (&Available) && ! noninteractive)
4947 kill (getpid (), SIGIO);
4948 #endif
4949
4950 if (! wait_proc)
4951 got_some_input |= nfds > 0;
4952
4953 /* If checking input just got us a size-change event from X,
4954 obey it now if we should. */
4955 if (read_kbd || ! NILP (wait_for_cell))
4956 do_pending_window_change (0);
4957
4958 /* Check for data from a process. */
4959 if (no_avail || nfds == 0)
4960 continue;
4961
4962 /* Really FIRST_PROC_DESC should be 0 on Unix,
4963 but this is safer in the short run. */
4964 for (channel = 0; channel <= max_process_desc; channel++)
4965 {
4966 if (FD_ISSET (channel, &Available)
4967 && FD_ISSET (channel, &non_keyboard_wait_mask))
4968 {
4969 int nread;
4970
4971 /* If waiting for this channel, arrange to return as
4972 soon as no more input to be processed. No more
4973 waiting. */
4974 if (wait_channel == channel)
4975 {
4976 wait_channel = -1;
4977 time_limit = -1;
4978 got_some_input = 1;
4979 }
4980 proc = chan_process[channel];
4981 if (NILP (proc))
4982 continue;
4983
4984 /* If this is a server stream socket, accept connection. */
4985 if (EQ (XPROCESS (proc)->status, Qlisten))
4986 {
4987 server_accept_connection (proc, channel);
4988 continue;
4989 }
4990
4991 /* Read data from the process, starting with our
4992 buffered-ahead character if we have one. */
4993
4994 nread = read_process_output (proc, channel);
4995 if (nread > 0)
4996 {
4997 /* Since read_process_output can run a filter,
4998 which can call accept-process-output,
4999 don't try to read from any other processes
5000 before doing the select again. */
5001 FD_ZERO (&Available);
5002
5003 if (do_display)
5004 redisplay_preserve_echo_area (12);
5005 }
5006 #ifdef EWOULDBLOCK
5007 else if (nread == -1 && errno == EWOULDBLOCK)
5008 ;
5009 #endif
5010 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
5011 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
5012 #ifdef O_NONBLOCK
5013 else if (nread == -1 && errno == EAGAIN)
5014 ;
5015 #else
5016 #ifdef O_NDELAY
5017 else if (nread == -1 && errno == EAGAIN)
5018 ;
5019 /* Note that we cannot distinguish between no input
5020 available now and a closed pipe.
5021 With luck, a closed pipe will be accompanied by
5022 subprocess termination and SIGCHLD. */
5023 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
5024 ;
5025 #endif /* O_NDELAY */
5026 #endif /* O_NONBLOCK */
5027 #ifdef HAVE_PTYS
5028 /* On some OSs with ptys, when the process on one end of
5029 a pty exits, the other end gets an error reading with
5030 errno = EIO instead of getting an EOF (0 bytes read).
5031 Therefore, if we get an error reading and errno =
5032 EIO, just continue, because the child process has
5033 exited and should clean itself up soon (e.g. when we
5034 get a SIGCHLD).
5035
5036 However, it has been known to happen that the SIGCHLD
5037 got lost. So raise the signal again just in case.
5038 It can't hurt. */
5039 else if (nread == -1 && errno == EIO)
5040 {
5041 /* Clear the descriptor now, so we only raise the signal once. */
5042 FD_CLR (channel, &input_wait_mask);
5043 FD_CLR (channel, &non_keyboard_wait_mask);
5044
5045 kill (getpid (), SIGCHLD);
5046 }
5047 #endif /* HAVE_PTYS */
5048 /* If we can detect process termination, don't consider the process
5049 gone just because its pipe is closed. */
5050 #ifdef SIGCHLD
5051 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
5052 ;
5053 #endif
5054 else
5055 {
5056 /* Preserve status of processes already terminated. */
5057 XPROCESS (proc)->tick = ++process_tick;
5058 deactivate_process (proc);
5059 if (XPROCESS (proc)->raw_status_new)
5060 update_status (XPROCESS (proc));
5061 if (EQ (XPROCESS (proc)->status, Qrun))
5062 XPROCESS (proc)->status
5063 = Fcons (Qexit, Fcons (make_number (256), Qnil));
5064 }
5065 }
5066 #ifdef NON_BLOCKING_CONNECT
5067 if (check_connect && FD_ISSET (channel, &Connecting)
5068 && FD_ISSET (channel, &connect_wait_mask))
5069 {
5070 struct Lisp_Process *p;
5071
5072 FD_CLR (channel, &connect_wait_mask);
5073 if (--num_pending_connects < 0)
5074 abort ();
5075
5076 proc = chan_process[channel];
5077 if (NILP (proc))
5078 continue;
5079
5080 p = XPROCESS (proc);
5081
5082 #ifdef GNU_LINUX
5083 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5084 So only use it on systems where it is known to work. */
5085 {
5086 int xlen = sizeof(xerrno);
5087 if (getsockopt(channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5088 xerrno = errno;
5089 }
5090 #else
5091 {
5092 struct sockaddr pname;
5093 int pnamelen = sizeof(pname);
5094
5095 /* If connection failed, getpeername will fail. */
5096 xerrno = 0;
5097 if (getpeername(channel, &pname, &pnamelen) < 0)
5098 {
5099 /* Obtain connect failure code through error slippage. */
5100 char dummy;
5101 xerrno = errno;
5102 if (errno == ENOTCONN && read(channel, &dummy, 1) < 0)
5103 xerrno = errno;
5104 }
5105 }
5106 #endif
5107 if (xerrno)
5108 {
5109 p->tick = ++process_tick;
5110 p->status = Fcons (Qfailed, Fcons (make_number (xerrno), Qnil));
5111 deactivate_process (proc);
5112 }
5113 else
5114 {
5115 p->status = Qrun;
5116 /* Execute the sentinel here. If we had relied on
5117 status_notify to do it later, it will read input
5118 from the process before calling the sentinel. */
5119 exec_sentinel (proc, build_string ("open\n"));
5120 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
5121 {
5122 FD_SET (p->infd, &input_wait_mask);
5123 FD_SET (p->infd, &non_keyboard_wait_mask);
5124 }
5125 }
5126 }
5127 #endif /* NON_BLOCKING_CONNECT */
5128 } /* end for each file descriptor */
5129 } /* end while exit conditions not met */
5130
5131 unbind_to (count, Qnil);
5132
5133 /* If calling from keyboard input, do not quit
5134 since we want to return C-g as an input character.
5135 Otherwise, do pending quit if requested. */
5136 if (read_kbd >= 0)
5137 {
5138 /* Prevent input_pending from remaining set if we quit. */
5139 clear_input_pending ();
5140 QUIT;
5141 }
5142
5143 return got_some_input;
5144 }
5145 \f
5146 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5147
5148 static Lisp_Object
5149 read_process_output_call (fun_and_args)
5150 Lisp_Object fun_and_args;
5151 {
5152 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5153 }
5154
5155 static Lisp_Object
5156 read_process_output_error_handler (error)
5157 Lisp_Object error;
5158 {
5159 cmd_error_internal (error, "error in process filter: ");
5160 Vinhibit_quit = Qt;
5161 update_echo_area ();
5162 Fsleep_for (make_number (2), Qnil);
5163 return Qt;
5164 }
5165
5166 /* Read pending output from the process channel,
5167 starting with our buffered-ahead character if we have one.
5168 Yield number of decoded characters read.
5169
5170 This function reads at most 4096 characters.
5171 If you want to read all available subprocess output,
5172 you must call it repeatedly until it returns zero.
5173
5174 The characters read are decoded according to PROC's coding-system
5175 for decoding. */
5176
5177 static int
5178 read_process_output (proc, channel)
5179 Lisp_Object proc;
5180 register int channel;
5181 {
5182 register int nbytes;
5183 char *chars;
5184 register Lisp_Object outstream;
5185 register struct buffer *old = current_buffer;
5186 register struct Lisp_Process *p = XPROCESS (proc);
5187 register int opoint;
5188 struct coding_system *coding = proc_decode_coding_system[channel];
5189 int carryover = p->decoding_carryover;
5190 int readmax = 4096;
5191
5192 chars = (char *) alloca (carryover + readmax);
5193 if (carryover)
5194 /* See the comment above. */
5195 bcopy (SDATA (p->decoding_buf), chars, carryover);
5196
5197 #ifdef DATAGRAM_SOCKETS
5198 /* We have a working select, so proc_buffered_char is always -1. */
5199 if (DATAGRAM_CHAN_P (channel))
5200 {
5201 int len = datagram_address[channel].len;
5202 nbytes = recvfrom (channel, chars + carryover, readmax,
5203 0, datagram_address[channel].sa, &len);
5204 }
5205 else
5206 #endif
5207 if (proc_buffered_char[channel] < 0)
5208 {
5209 nbytes = emacs_read (channel, chars + carryover, readmax);
5210 #ifdef ADAPTIVE_READ_BUFFERING
5211 if (nbytes > 0 && p->adaptive_read_buffering)
5212 {
5213 int delay = p->read_output_delay;
5214 if (nbytes < 256)
5215 {
5216 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5217 {
5218 if (delay == 0)
5219 process_output_delay_count++;
5220 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5221 }
5222 }
5223 else if (delay > 0 && (nbytes == readmax))
5224 {
5225 delay -= READ_OUTPUT_DELAY_INCREMENT;
5226 if (delay == 0)
5227 process_output_delay_count--;
5228 }
5229 p->read_output_delay = delay;
5230 if (delay)
5231 {
5232 p->read_output_skip = 1;
5233 process_output_skip = 1;
5234 }
5235 }
5236 #endif
5237 }
5238 else
5239 {
5240 chars[carryover] = proc_buffered_char[channel];
5241 proc_buffered_char[channel] = -1;
5242 nbytes = emacs_read (channel, chars + carryover + 1, readmax - 1);
5243 if (nbytes < 0)
5244 nbytes = 1;
5245 else
5246 nbytes = nbytes + 1;
5247 }
5248
5249 p->decoding_carryover = 0;
5250
5251 /* At this point, NBYTES holds number of bytes just received
5252 (including the one in proc_buffered_char[channel]). */
5253 if (nbytes <= 0)
5254 {
5255 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5256 return nbytes;
5257 coding->mode |= CODING_MODE_LAST_BLOCK;
5258 }
5259
5260 /* Now set NBYTES how many bytes we must decode. */
5261 nbytes += carryover;
5262
5263 /* Read and dispose of the process output. */
5264 outstream = p->filter;
5265 if (!NILP (outstream))
5266 {
5267 /* We inhibit quit here instead of just catching it so that
5268 hitting ^G when a filter happens to be running won't screw
5269 it up. */
5270 int count = SPECPDL_INDEX ();
5271 Lisp_Object odeactivate;
5272 Lisp_Object obuffer, okeymap;
5273 Lisp_Object text;
5274 int outer_running_asynch_code = running_asynch_code;
5275 int waiting = waiting_for_user_input_p;
5276
5277 /* No need to gcpro these, because all we do with them later
5278 is test them for EQness, and none of them should be a string. */
5279 odeactivate = Vdeactivate_mark;
5280 XSETBUFFER (obuffer, current_buffer);
5281 okeymap = current_buffer->keymap;
5282
5283 specbind (Qinhibit_quit, Qt);
5284 specbind (Qlast_nonmenu_event, Qt);
5285
5286 /* In case we get recursively called,
5287 and we already saved the match data nonrecursively,
5288 save the same match data in safely recursive fashion. */
5289 if (outer_running_asynch_code)
5290 {
5291 Lisp_Object tem;
5292 /* Don't clobber the CURRENT match data, either! */
5293 tem = Fmatch_data (Qnil, Qnil, Qnil);
5294 restore_search_regs ();
5295 record_unwind_save_match_data ();
5296 Fset_match_data (tem, Qt);
5297 }
5298
5299 /* For speed, if a search happens within this code,
5300 save the match data in a special nonrecursive fashion. */
5301 running_asynch_code = 1;
5302
5303 decode_coding_c_string (coding, chars, nbytes, Qt);
5304 text = coding->dst_object;
5305 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5306 /* A new coding system might be found. */
5307 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5308 {
5309 p->decode_coding_system = Vlast_coding_system_used;
5310
5311 /* Don't call setup_coding_system for
5312 proc_decode_coding_system[channel] here. It is done in
5313 detect_coding called via decode_coding above. */
5314
5315 /* If a coding system for encoding is not yet decided, we set
5316 it as the same as coding-system for decoding.
5317
5318 But, before doing that we must check if
5319 proc_encode_coding_system[p->outfd] surely points to a
5320 valid memory because p->outfd will be changed once EOF is
5321 sent to the process. */
5322 if (NILP (p->encode_coding_system)
5323 && proc_encode_coding_system[p->outfd])
5324 {
5325 p->encode_coding_system
5326 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5327 setup_coding_system (p->encode_coding_system,
5328 proc_encode_coding_system[p->outfd]);
5329 }
5330 }
5331
5332 if (coding->carryover_bytes > 0)
5333 {
5334 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5335 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5336 bcopy (coding->carryover, SDATA (p->decoding_buf),
5337 coding->carryover_bytes);
5338 p->decoding_carryover = coding->carryover_bytes;
5339 }
5340 if (SBYTES (text) > 0)
5341 internal_condition_case_1 (read_process_output_call,
5342 Fcons (outstream,
5343 Fcons (proc, Fcons (text, Qnil))),
5344 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5345 read_process_output_error_handler);
5346
5347 /* If we saved the match data nonrecursively, restore it now. */
5348 restore_search_regs ();
5349 running_asynch_code = outer_running_asynch_code;
5350
5351 /* Handling the process output should not deactivate the mark. */
5352 Vdeactivate_mark = odeactivate;
5353
5354 /* Restore waiting_for_user_input_p as it was
5355 when we were called, in case the filter clobbered it. */
5356 waiting_for_user_input_p = waiting;
5357
5358 #if 0 /* Call record_asynch_buffer_change unconditionally,
5359 because we might have changed minor modes or other things
5360 that affect key bindings. */
5361 if (! EQ (Fcurrent_buffer (), obuffer)
5362 || ! EQ (current_buffer->keymap, okeymap))
5363 #endif
5364 /* But do it only if the caller is actually going to read events.
5365 Otherwise there's no need to make him wake up, and it could
5366 cause trouble (for example it would make sit_for return). */
5367 if (waiting_for_user_input_p == -1)
5368 record_asynch_buffer_change ();
5369
5370 unbind_to (count, Qnil);
5371 return nbytes;
5372 }
5373
5374 /* If no filter, write into buffer if it isn't dead. */
5375 if (!NILP (p->buffer) && !NILP (XBUFFER (p->buffer)->name))
5376 {
5377 Lisp_Object old_read_only;
5378 int old_begv, old_zv;
5379 int old_begv_byte, old_zv_byte;
5380 Lisp_Object odeactivate;
5381 int before, before_byte;
5382 int opoint_byte;
5383 Lisp_Object text;
5384 struct buffer *b;
5385
5386 odeactivate = Vdeactivate_mark;
5387
5388 Fset_buffer (p->buffer);
5389 opoint = PT;
5390 opoint_byte = PT_BYTE;
5391 old_read_only = current_buffer->read_only;
5392 old_begv = BEGV;
5393 old_zv = ZV;
5394 old_begv_byte = BEGV_BYTE;
5395 old_zv_byte = ZV_BYTE;
5396
5397 current_buffer->read_only = Qnil;
5398
5399 /* Insert new output into buffer
5400 at the current end-of-output marker,
5401 thus preserving logical ordering of input and output. */
5402 if (XMARKER (p->mark)->buffer)
5403 SET_PT_BOTH (clip_to_bounds (BEGV, marker_position (p->mark), ZV),
5404 clip_to_bounds (BEGV_BYTE, marker_byte_position (p->mark),
5405 ZV_BYTE));
5406 else
5407 SET_PT_BOTH (ZV, ZV_BYTE);
5408 before = PT;
5409 before_byte = PT_BYTE;
5410
5411 /* If the output marker is outside of the visible region, save
5412 the restriction and widen. */
5413 if (! (BEGV <= PT && PT <= ZV))
5414 Fwiden ();
5415
5416 decode_coding_c_string (coding, chars, nbytes, Qt);
5417 text = coding->dst_object;
5418 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5419 /* A new coding system might be found. See the comment in the
5420 similar code in the previous `if' block. */
5421 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5422 {
5423 p->decode_coding_system = Vlast_coding_system_used;
5424 if (NILP (p->encode_coding_system)
5425 && proc_encode_coding_system[p->outfd])
5426 {
5427 p->encode_coding_system
5428 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5429 setup_coding_system (p->encode_coding_system,
5430 proc_encode_coding_system[p->outfd]);
5431 }
5432 }
5433 if (coding->carryover_bytes > 0)
5434 {
5435 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5436 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5437 bcopy (coding->carryover, SDATA (p->decoding_buf),
5438 coding->carryover_bytes);
5439 p->decoding_carryover = coding->carryover_bytes;
5440 }
5441 /* Adjust the multibyteness of TEXT to that of the buffer. */
5442 if (NILP (current_buffer->enable_multibyte_characters)
5443 != ! STRING_MULTIBYTE (text))
5444 text = (STRING_MULTIBYTE (text)
5445 ? Fstring_as_unibyte (text)
5446 : Fstring_to_multibyte (text));
5447 /* Insert before markers in case we are inserting where
5448 the buffer's mark is, and the user's next command is Meta-y. */
5449 insert_from_string_before_markers (text, 0, 0,
5450 SCHARS (text), SBYTES (text), 0);
5451
5452 /* Make sure the process marker's position is valid when the
5453 process buffer is changed in the signal_after_change above.
5454 W3 is known to do that. */
5455 if (BUFFERP (p->buffer)
5456 && (b = XBUFFER (p->buffer), b != current_buffer))
5457 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5458 else
5459 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5460
5461 update_mode_lines++;
5462
5463 /* Make sure opoint and the old restrictions
5464 float ahead of any new text just as point would. */
5465 if (opoint >= before)
5466 {
5467 opoint += PT - before;
5468 opoint_byte += PT_BYTE - before_byte;
5469 }
5470 if (old_begv > before)
5471 {
5472 old_begv += PT - before;
5473 old_begv_byte += PT_BYTE - before_byte;
5474 }
5475 if (old_zv >= before)
5476 {
5477 old_zv += PT - before;
5478 old_zv_byte += PT_BYTE - before_byte;
5479 }
5480
5481 /* If the restriction isn't what it should be, set it. */
5482 if (old_begv != BEGV || old_zv != ZV)
5483 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5484
5485 /* Handling the process output should not deactivate the mark. */
5486 Vdeactivate_mark = odeactivate;
5487
5488 current_buffer->read_only = old_read_only;
5489 SET_PT_BOTH (opoint, opoint_byte);
5490 set_buffer_internal (old);
5491 }
5492 return nbytes;
5493 }
5494
5495 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p, Swaiting_for_user_input_p,
5496 0, 0, 0,
5497 doc: /* Returns non-nil if Emacs is waiting for input from the user.
5498 This is intended for use by asynchronous process output filters and sentinels. */)
5499 ()
5500 {
5501 return (waiting_for_user_input_p ? Qt : Qnil);
5502 }
5503 \f
5504 /* Sending data to subprocess */
5505
5506 jmp_buf send_process_frame;
5507 Lisp_Object process_sent_to;
5508
5509 SIGTYPE
5510 send_process_trap ()
5511 {
5512 SIGNAL_THREAD_CHECK (SIGPIPE);
5513 sigunblock (sigmask (SIGPIPE));
5514 longjmp (send_process_frame, 1);
5515 }
5516
5517 /* Send some data to process PROC.
5518 BUF is the beginning of the data; LEN is the number of characters.
5519 OBJECT is the Lisp object that the data comes from. If OBJECT is
5520 nil or t, it means that the data comes from C string.
5521
5522 If OBJECT is not nil, the data is encoded by PROC's coding-system
5523 for encoding before it is sent.
5524
5525 This function can evaluate Lisp code and can garbage collect. */
5526
5527 static void
5528 send_process (proc, buf, len, object)
5529 volatile Lisp_Object proc;
5530 unsigned char *volatile buf;
5531 volatile int len;
5532 volatile Lisp_Object object;
5533 {
5534 /* Use volatile to protect variables from being clobbered by longjmp. */
5535 struct Lisp_Process *p = XPROCESS (proc);
5536 int rv;
5537 struct coding_system *coding;
5538 struct gcpro gcpro1;
5539 SIGTYPE (*volatile old_sigpipe) ();
5540
5541 GCPRO1 (object);
5542
5543 if (p->raw_status_new)
5544 update_status (p);
5545 if (! EQ (p->status, Qrun))
5546 error ("Process %s not running", SDATA (p->name));
5547 if (p->outfd < 0)
5548 error ("Output file descriptor of %s is closed", SDATA (p->name));
5549
5550 coding = proc_encode_coding_system[p->outfd];
5551 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5552
5553 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5554 || (BUFFERP (object)
5555 && !NILP (XBUFFER (object)->enable_multibyte_characters))
5556 || EQ (object, Qt))
5557 {
5558 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5559 /* The coding system for encoding was changed to raw-text
5560 because we sent a unibyte text previously. Now we are
5561 sending a multibyte text, thus we must encode it by the
5562 original coding system specified for the current process. */
5563 setup_coding_system (p->encode_coding_system, coding);
5564 coding->src_multibyte = 1;
5565 }
5566 else
5567 {
5568 /* For sending a unibyte text, character code conversion should
5569 not take place but EOL conversion should. So, setup raw-text
5570 or one of the subsidiary if we have not yet done it. */
5571 if (CODING_REQUIRE_ENCODING (coding))
5572 {
5573 if (CODING_REQUIRE_FLUSHING (coding))
5574 {
5575 /* But, before changing the coding, we must flush out data. */
5576 coding->mode |= CODING_MODE_LAST_BLOCK;
5577 send_process (proc, "", 0, Qt);
5578 coding->mode &= CODING_MODE_LAST_BLOCK;
5579 }
5580 setup_coding_system (raw_text_coding_system
5581 (Vlast_coding_system_used),
5582 coding);
5583 coding->src_multibyte = 0;
5584 }
5585 }
5586 coding->dst_multibyte = 0;
5587
5588 if (CODING_REQUIRE_ENCODING (coding))
5589 {
5590 coding->dst_object = Qt;
5591 if (BUFFERP (object))
5592 {
5593 int from_byte, from, to;
5594 int save_pt, save_pt_byte;
5595 struct buffer *cur = current_buffer;
5596
5597 set_buffer_internal (XBUFFER (object));
5598 save_pt = PT, save_pt_byte = PT_BYTE;
5599
5600 from_byte = PTR_BYTE_POS (buf);
5601 from = BYTE_TO_CHAR (from_byte);
5602 to = BYTE_TO_CHAR (from_byte + len);
5603 TEMP_SET_PT_BOTH (from, from_byte);
5604 encode_coding_object (coding, object, from, from_byte,
5605 to, from_byte + len, Qt);
5606 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5607 set_buffer_internal (cur);
5608 }
5609 else if (STRINGP (object))
5610 {
5611 encode_coding_string (coding, object, 1);
5612 }
5613 else
5614 {
5615 coding->dst_object = make_unibyte_string (buf, len);
5616 coding->produced = len;
5617 }
5618
5619 len = coding->produced;
5620 buf = SDATA (coding->dst_object);
5621 }
5622
5623 if (pty_max_bytes == 0)
5624 {
5625 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
5626 pty_max_bytes = fpathconf (p->outfd, _PC_MAX_CANON);
5627 if (pty_max_bytes < 0)
5628 pty_max_bytes = 250;
5629 #else
5630 pty_max_bytes = 250;
5631 #endif
5632 /* Deduct one, to leave space for the eof. */
5633 pty_max_bytes--;
5634 }
5635
5636 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
5637 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
5638 when returning with longjmp despite being declared volatile. */
5639 if (!setjmp (send_process_frame))
5640 {
5641 process_sent_to = proc;
5642 while (len > 0)
5643 {
5644 int this = len;
5645
5646 /* Decide how much data we can send in one batch.
5647 Long lines need to be split into multiple batches. */
5648 if (p->pty_flag)
5649 {
5650 /* Starting this at zero is always correct when not the first
5651 iteration because the previous iteration ended by sending C-d.
5652 It may not be correct for the first iteration
5653 if a partial line was sent in a separate send_process call.
5654 If that proves worth handling, we need to save linepos
5655 in the process object. */
5656 int linepos = 0;
5657 unsigned char *ptr = (unsigned char *) buf;
5658 unsigned char *end = (unsigned char *) buf + len;
5659
5660 /* Scan through this text for a line that is too long. */
5661 while (ptr != end && linepos < pty_max_bytes)
5662 {
5663 if (*ptr == '\n')
5664 linepos = 0;
5665 else
5666 linepos++;
5667 ptr++;
5668 }
5669 /* If we found one, break the line there
5670 and put in a C-d to force the buffer through. */
5671 this = ptr - buf;
5672 }
5673
5674 /* Send this batch, using one or more write calls. */
5675 while (this > 0)
5676 {
5677 int outfd = p->outfd;
5678 old_sigpipe = (SIGTYPE (*) ()) signal (SIGPIPE, send_process_trap);
5679 #ifdef DATAGRAM_SOCKETS
5680 if (DATAGRAM_CHAN_P (outfd))
5681 {
5682 rv = sendto (outfd, (char *) buf, this,
5683 0, datagram_address[outfd].sa,
5684 datagram_address[outfd].len);
5685 if (rv < 0 && errno == EMSGSIZE)
5686 {
5687 signal (SIGPIPE, old_sigpipe);
5688 report_file_error ("sending datagram",
5689 Fcons (proc, Qnil));
5690 }
5691 }
5692 else
5693 #endif
5694 {
5695 rv = emacs_write (outfd, (char *) buf, this);
5696 #ifdef ADAPTIVE_READ_BUFFERING
5697 if (p->read_output_delay > 0
5698 && p->adaptive_read_buffering == 1)
5699 {
5700 p->read_output_delay = 0;
5701 process_output_delay_count--;
5702 p->read_output_skip = 0;
5703 }
5704 #endif
5705 }
5706 signal (SIGPIPE, old_sigpipe);
5707
5708 if (rv < 0)
5709 {
5710 if (0
5711 #ifdef EWOULDBLOCK
5712 || errno == EWOULDBLOCK
5713 #endif
5714 #ifdef EAGAIN
5715 || errno == EAGAIN
5716 #endif
5717 )
5718 /* Buffer is full. Wait, accepting input;
5719 that may allow the program
5720 to finish doing output and read more. */
5721 {
5722 int offset = 0;
5723
5724 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5725 /* A gross hack to work around a bug in FreeBSD.
5726 In the following sequence, read(2) returns
5727 bogus data:
5728
5729 write(2) 1022 bytes
5730 write(2) 954 bytes, get EAGAIN
5731 read(2) 1024 bytes in process_read_output
5732 read(2) 11 bytes in process_read_output
5733
5734 That is, read(2) returns more bytes than have
5735 ever been written successfully. The 1033 bytes
5736 read are the 1022 bytes written successfully
5737 after processing (for example with CRs added if
5738 the terminal is set up that way which it is
5739 here). The same bytes will be seen again in a
5740 later read(2), without the CRs. */
5741
5742 if (errno == EAGAIN)
5743 {
5744 int flags = FWRITE;
5745 ioctl (p->outfd, TIOCFLUSH, &flags);
5746 }
5747 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5748
5749 /* Running filters might relocate buffers or strings.
5750 Arrange to relocate BUF. */
5751 if (BUFFERP (object))
5752 offset = BUF_PTR_BYTE_POS (XBUFFER (object), buf);
5753 else if (STRINGP (object))
5754 offset = buf - SDATA (object);
5755
5756 #ifdef EMACS_HAS_USECS
5757 wait_reading_process_output (0, 20000, 0, 0, Qnil, NULL, 0);
5758 #else
5759 wait_reading_process_output (1, 0, 0, 0, Qnil, NULL, 0);
5760 #endif
5761
5762 if (BUFFERP (object))
5763 buf = BUF_BYTE_ADDRESS (XBUFFER (object), offset);
5764 else if (STRINGP (object))
5765 buf = offset + SDATA (object);
5766
5767 rv = 0;
5768 }
5769 else
5770 /* This is a real error. */
5771 report_file_error ("writing to process", Fcons (proc, Qnil));
5772 }
5773 buf += rv;
5774 len -= rv;
5775 this -= rv;
5776 }
5777
5778 /* If we sent just part of the string, put in an EOF (C-d)
5779 to force it through, before we send the rest. */
5780 if (len > 0)
5781 Fprocess_send_eof (proc);
5782 }
5783 }
5784 else
5785 {
5786 signal (SIGPIPE, old_sigpipe);
5787 proc = process_sent_to;
5788 p = XPROCESS (proc);
5789 p->raw_status_new = 0;
5790 p->status = Fcons (Qexit, Fcons (make_number (256), Qnil));
5791 p->tick = ++process_tick;
5792 deactivate_process (proc);
5793 error ("SIGPIPE raised on process %s; closed it", SDATA (p->name));
5794 }
5795
5796 UNGCPRO;
5797 }
5798
5799 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5800 3, 3, 0,
5801 doc: /* Send current contents of region as input to PROCESS.
5802 PROCESS may be a process, a buffer, the name of a process or buffer, or
5803 nil, indicating the current buffer's process.
5804 Called from program, takes three arguments, PROCESS, START and END.
5805 If the region is more than 500 characters long,
5806 it is sent in several bunches. This may happen even for shorter regions.
5807 Output from processes can arrive in between bunches. */)
5808 (process, start, end)
5809 Lisp_Object process, start, end;
5810 {
5811 Lisp_Object proc;
5812 int start1, end1;
5813
5814 proc = get_process (process);
5815 validate_region (&start, &end);
5816
5817 if (XINT (start) < GPT && XINT (end) > GPT)
5818 move_gap (XINT (start));
5819
5820 start1 = CHAR_TO_BYTE (XINT (start));
5821 end1 = CHAR_TO_BYTE (XINT (end));
5822 send_process (proc, BYTE_POS_ADDR (start1), end1 - start1,
5823 Fcurrent_buffer ());
5824
5825 return Qnil;
5826 }
5827
5828 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5829 2, 2, 0,
5830 doc: /* Send PROCESS the contents of STRING as input.
5831 PROCESS may be a process, a buffer, the name of a process or buffer, or
5832 nil, indicating the current buffer's process.
5833 If STRING is more than 500 characters long,
5834 it is sent in several bunches. This may happen even for shorter strings.
5835 Output from processes can arrive in between bunches. */)
5836 (process, string)
5837 Lisp_Object process, string;
5838 {
5839 Lisp_Object proc;
5840 CHECK_STRING (string);
5841 proc = get_process (process);
5842 send_process (proc, SDATA (string),
5843 SBYTES (string), string);
5844 return Qnil;
5845 }
5846 \f
5847 /* Return the foreground process group for the tty/pty that
5848 the process P uses. */
5849 static int
5850 emacs_get_tty_pgrp (p)
5851 struct Lisp_Process *p;
5852 {
5853 int gid = -1;
5854
5855 #ifdef TIOCGPGRP
5856 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5857 {
5858 int fd;
5859 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5860 master side. Try the slave side. */
5861 fd = emacs_open (SDATA (p->tty_name), O_RDONLY, 0);
5862
5863 if (fd != -1)
5864 {
5865 ioctl (fd, TIOCGPGRP, &gid);
5866 emacs_close (fd);
5867 }
5868 }
5869 #endif /* defined (TIOCGPGRP ) */
5870
5871 return gid;
5872 }
5873
5874 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5875 Sprocess_running_child_p, 0, 1, 0,
5876 doc: /* Return t if PROCESS has given the terminal to a child.
5877 If the operating system does not make it possible to find out,
5878 return t unconditionally. */)
5879 (process)
5880 Lisp_Object process;
5881 {
5882 /* Initialize in case ioctl doesn't exist or gives an error,
5883 in a way that will cause returning t. */
5884 int gid;
5885 Lisp_Object proc;
5886 struct Lisp_Process *p;
5887
5888 proc = get_process (process);
5889 p = XPROCESS (proc);
5890
5891 if (!EQ (p->type, Qreal))
5892 error ("Process %s is not a subprocess",
5893 SDATA (p->name));
5894 if (p->infd < 0)
5895 error ("Process %s is not active",
5896 SDATA (p->name));
5897
5898 gid = emacs_get_tty_pgrp (p);
5899
5900 if (gid == p->pid)
5901 return Qnil;
5902 return Qt;
5903 }
5904 \f
5905 /* send a signal number SIGNO to PROCESS.
5906 If CURRENT_GROUP is t, that means send to the process group
5907 that currently owns the terminal being used to communicate with PROCESS.
5908 This is used for various commands in shell mode.
5909 If CURRENT_GROUP is lambda, that means send to the process group
5910 that currently owns the terminal, but only if it is NOT the shell itself.
5911
5912 If NOMSG is zero, insert signal-announcements into process's buffers
5913 right away.
5914
5915 If we can, we try to signal PROCESS by sending control characters
5916 down the pty. This allows us to signal inferiors who have changed
5917 their uid, for which killpg would return an EPERM error. */
5918
5919 static void
5920 process_send_signal (process, signo, current_group, nomsg)
5921 Lisp_Object process;
5922 int signo;
5923 Lisp_Object current_group;
5924 int nomsg;
5925 {
5926 Lisp_Object proc;
5927 register struct Lisp_Process *p;
5928 int gid;
5929 int no_pgrp = 0;
5930
5931 proc = get_process (process);
5932 p = XPROCESS (proc);
5933
5934 if (!EQ (p->type, Qreal))
5935 error ("Process %s is not a subprocess",
5936 SDATA (p->name));
5937 if (p->infd < 0)
5938 error ("Process %s is not active",
5939 SDATA (p->name));
5940
5941 if (!p->pty_flag)
5942 current_group = Qnil;
5943
5944 /* If we are using pgrps, get a pgrp number and make it negative. */
5945 if (NILP (current_group))
5946 /* Send the signal to the shell's process group. */
5947 gid = p->pid;
5948 else
5949 {
5950 #ifdef SIGNALS_VIA_CHARACTERS
5951 /* If possible, send signals to the entire pgrp
5952 by sending an input character to it. */
5953
5954 /* TERMIOS is the latest and bestest, and seems most likely to
5955 work. If the system has it, use it. */
5956 #ifdef HAVE_TERMIOS
5957 struct termios t;
5958 cc_t *sig_char = NULL;
5959
5960 tcgetattr (p->infd, &t);
5961
5962 switch (signo)
5963 {
5964 case SIGINT:
5965 sig_char = &t.c_cc[VINTR];
5966 break;
5967
5968 case SIGQUIT:
5969 sig_char = &t.c_cc[VQUIT];
5970 break;
5971
5972 case SIGTSTP:
5973 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5974 sig_char = &t.c_cc[VSWTCH];
5975 #else
5976 sig_char = &t.c_cc[VSUSP];
5977 #endif
5978 break;
5979 }
5980
5981 if (sig_char && *sig_char != CDISABLE)
5982 {
5983 send_process (proc, sig_char, 1, Qnil);
5984 return;
5985 }
5986 /* If we can't send the signal with a character,
5987 fall through and send it another way. */
5988 #else /* ! HAVE_TERMIOS */
5989
5990 /* On Berkeley descendants, the following IOCTL's retrieve the
5991 current control characters. */
5992 #if defined (TIOCGLTC) && defined (TIOCGETC)
5993
5994 struct tchars c;
5995 struct ltchars lc;
5996
5997 switch (signo)
5998 {
5999 case SIGINT:
6000 ioctl (p->infd, TIOCGETC, &c);
6001 send_process (proc, &c.t_intrc, 1, Qnil);
6002 return;
6003 case SIGQUIT:
6004 ioctl (p->infd, TIOCGETC, &c);
6005 send_process (proc, &c.t_quitc, 1, Qnil);
6006 return;
6007 #ifdef SIGTSTP
6008 case SIGTSTP:
6009 ioctl (p->infd, TIOCGLTC, &lc);
6010 send_process (proc, &lc.t_suspc, 1, Qnil);
6011 return;
6012 #endif /* ! defined (SIGTSTP) */
6013 }
6014
6015 #else /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
6016
6017 /* On SYSV descendants, the TCGETA ioctl retrieves the current control
6018 characters. */
6019 #ifdef TCGETA
6020 struct termio t;
6021 switch (signo)
6022 {
6023 case SIGINT:
6024 ioctl (p->infd, TCGETA, &t);
6025 send_process (proc, &t.c_cc[VINTR], 1, Qnil);
6026 return;
6027 case SIGQUIT:
6028 ioctl (p->infd, TCGETA, &t);
6029 send_process (proc, &t.c_cc[VQUIT], 1, Qnil);
6030 return;
6031 #ifdef SIGTSTP
6032 case SIGTSTP:
6033 ioctl (p->infd, TCGETA, &t);
6034 send_process (proc, &t.c_cc[VSWTCH], 1, Qnil);
6035 return;
6036 #endif /* ! defined (SIGTSTP) */
6037 }
6038 #else /* ! defined (TCGETA) */
6039 Your configuration files are messed up.
6040 /* If your system configuration files define SIGNALS_VIA_CHARACTERS,
6041 you'd better be using one of the alternatives above! */
6042 #endif /* ! defined (TCGETA) */
6043 #endif /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
6044 /* In this case, the code above should alway return. */
6045 abort ();
6046 #endif /* ! defined HAVE_TERMIOS */
6047
6048 /* The code above may fall through if it can't
6049 handle the signal. */
6050 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6051
6052 #ifdef TIOCGPGRP
6053 /* Get the current pgrp using the tty itself, if we have that.
6054 Otherwise, use the pty to get the pgrp.
6055 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6056 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6057 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6058 His patch indicates that if TIOCGPGRP returns an error, then
6059 we should just assume that p->pid is also the process group id. */
6060
6061 gid = emacs_get_tty_pgrp (p);
6062
6063 if (gid == -1)
6064 /* If we can't get the information, assume
6065 the shell owns the tty. */
6066 gid = p->pid;
6067
6068 /* It is not clear whether anything really can set GID to -1.
6069 Perhaps on some system one of those ioctls can or could do so.
6070 Or perhaps this is vestigial. */
6071 if (gid == -1)
6072 no_pgrp = 1;
6073 #else /* ! defined (TIOCGPGRP ) */
6074 /* Can't select pgrps on this system, so we know that
6075 the child itself heads the pgrp. */
6076 gid = p->pid;
6077 #endif /* ! defined (TIOCGPGRP ) */
6078
6079 /* If current_group is lambda, and the shell owns the terminal,
6080 don't send any signal. */
6081 if (EQ (current_group, Qlambda) && gid == p->pid)
6082 return;
6083 }
6084
6085 switch (signo)
6086 {
6087 #ifdef SIGCONT
6088 case SIGCONT:
6089 p->raw_status_new = 0;
6090 p->status = Qrun;
6091 p->tick = ++process_tick;
6092 if (!nomsg)
6093 status_notify (NULL);
6094 break;
6095 #endif /* ! defined (SIGCONT) */
6096 case SIGINT:
6097 case SIGQUIT:
6098 case SIGKILL:
6099 flush_pending_output (p->infd);
6100 break;
6101 }
6102
6103 /* If we don't have process groups, send the signal to the immediate
6104 subprocess. That isn't really right, but it's better than any
6105 obvious alternative. */
6106 if (no_pgrp)
6107 {
6108 kill (p->pid, signo);
6109 return;
6110 }
6111
6112 /* gid may be a pid, or minus a pgrp's number */
6113 #ifdef TIOCSIGSEND
6114 if (!NILP (current_group))
6115 {
6116 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
6117 EMACS_KILLPG (gid, signo);
6118 }
6119 else
6120 {
6121 gid = - p->pid;
6122 kill (gid, signo);
6123 }
6124 #else /* ! defined (TIOCSIGSEND) */
6125 EMACS_KILLPG (gid, signo);
6126 #endif /* ! defined (TIOCSIGSEND) */
6127 }
6128
6129 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6130 doc: /* Interrupt process PROCESS.
6131 PROCESS may be a process, a buffer, or the name of a process or buffer.
6132 No arg or nil means current buffer's process.
6133 Second arg CURRENT-GROUP non-nil means send signal to
6134 the current process-group of the process's controlling terminal
6135 rather than to the process's own process group.
6136 If the process is a shell, this means interrupt current subjob
6137 rather than the shell.
6138
6139 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6140 don't send the signal. */)
6141 (process, current_group)
6142 Lisp_Object process, current_group;
6143 {
6144 process_send_signal (process, SIGINT, current_group, 0);
6145 return process;
6146 }
6147
6148 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6149 doc: /* Kill process PROCESS. May be process or name of one.
6150 See function `interrupt-process' for more details on usage. */)
6151 (process, current_group)
6152 Lisp_Object process, current_group;
6153 {
6154 process_send_signal (process, SIGKILL, current_group, 0);
6155 return process;
6156 }
6157
6158 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6159 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6160 See function `interrupt-process' for more details on usage. */)
6161 (process, current_group)
6162 Lisp_Object process, current_group;
6163 {
6164 process_send_signal (process, SIGQUIT, current_group, 0);
6165 return process;
6166 }
6167
6168 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6169 doc: /* Stop process PROCESS. May be process or name of one.
6170 See function `interrupt-process' for more details on usage.
6171 If PROCESS is a network or serial process, inhibit handling of incoming
6172 traffic. */)
6173 (process, current_group)
6174 Lisp_Object process, current_group;
6175 {
6176 #ifdef HAVE_SOCKETS
6177 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6178 {
6179 struct Lisp_Process *p;
6180
6181 p = XPROCESS (process);
6182 if (NILP (p->command)
6183 && p->infd >= 0)
6184 {
6185 FD_CLR (p->infd, &input_wait_mask);
6186 FD_CLR (p->infd, &non_keyboard_wait_mask);
6187 }
6188 p->command = Qt;
6189 return process;
6190 }
6191 #endif
6192 #ifndef SIGTSTP
6193 error ("No SIGTSTP support");
6194 #else
6195 process_send_signal (process, SIGTSTP, current_group, 0);
6196 #endif
6197 return process;
6198 }
6199
6200 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6201 doc: /* Continue process PROCESS. May be process or name of one.
6202 See function `interrupt-process' for more details on usage.
6203 If PROCESS is a network or serial process, resume handling of incoming
6204 traffic. */)
6205 (process, current_group)
6206 Lisp_Object process, current_group;
6207 {
6208 #ifdef HAVE_SOCKETS
6209 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6210 {
6211 struct Lisp_Process *p;
6212
6213 p = XPROCESS (process);
6214 if (EQ (p->command, Qt)
6215 && p->infd >= 0
6216 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6217 {
6218 FD_SET (p->infd, &input_wait_mask);
6219 FD_SET (p->infd, &non_keyboard_wait_mask);
6220 #ifdef WINDOWSNT
6221 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6222 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6223 #endif
6224 #ifdef HAVE_TERMIOS
6225 tcflush (p->infd, TCIFLUSH);
6226 #endif
6227 }
6228 p->command = Qnil;
6229 return process;
6230 }
6231 #endif
6232 #ifdef SIGCONT
6233 process_send_signal (process, SIGCONT, current_group, 0);
6234 #else
6235 error ("No SIGCONT support");
6236 #endif
6237 return process;
6238 }
6239
6240 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6241 2, 2, "sProcess (name or number): \nnSignal code: ",
6242 doc: /* Send PROCESS the signal with code SIGCODE.
6243 PROCESS may also be a number specifying the process id of the
6244 process to signal; in this case, the process need not be a child of
6245 this Emacs.
6246 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6247 (process, sigcode)
6248 Lisp_Object process, sigcode;
6249 {
6250 pid_t pid;
6251
6252 if (INTEGERP (process))
6253 {
6254 pid = XINT (process);
6255 goto got_it;
6256 }
6257
6258 if (FLOATP (process))
6259 {
6260 pid = (pid_t) XFLOAT_DATA (process);
6261 goto got_it;
6262 }
6263
6264 if (STRINGP (process))
6265 {
6266 Lisp_Object tem;
6267 if (tem = Fget_process (process), NILP (tem))
6268 {
6269 pid = XINT (Fstring_to_number (process, make_number (10)));
6270 if (pid > 0)
6271 goto got_it;
6272 }
6273 process = tem;
6274 }
6275 else
6276 process = get_process (process);
6277
6278 if (NILP (process))
6279 return process;
6280
6281 CHECK_PROCESS (process);
6282 pid = XPROCESS (process)->pid;
6283 if (pid <= 0)
6284 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6285
6286 got_it:
6287
6288 #define parse_signal(NAME, VALUE) \
6289 else if (!xstrcasecmp (name, NAME)) \
6290 XSETINT (sigcode, VALUE)
6291
6292 if (INTEGERP (sigcode))
6293 ;
6294 else
6295 {
6296 unsigned char *name;
6297
6298 CHECK_SYMBOL (sigcode);
6299 name = SDATA (SYMBOL_NAME (sigcode));
6300
6301 if (!strncmp(name, "SIG", 3) || !strncmp(name, "sig", 3))
6302 name += 3;
6303
6304 if (0)
6305 ;
6306 #ifdef SIGUSR1
6307 parse_signal ("usr1", SIGUSR1);
6308 #endif
6309 #ifdef SIGUSR2
6310 parse_signal ("usr2", SIGUSR2);
6311 #endif
6312 #ifdef SIGTERM
6313 parse_signal ("term", SIGTERM);
6314 #endif
6315 #ifdef SIGHUP
6316 parse_signal ("hup", SIGHUP);
6317 #endif
6318 #ifdef SIGINT
6319 parse_signal ("int", SIGINT);
6320 #endif
6321 #ifdef SIGQUIT
6322 parse_signal ("quit", SIGQUIT);
6323 #endif
6324 #ifdef SIGILL
6325 parse_signal ("ill", SIGILL);
6326 #endif
6327 #ifdef SIGABRT
6328 parse_signal ("abrt", SIGABRT);
6329 #endif
6330 #ifdef SIGEMT
6331 parse_signal ("emt", SIGEMT);
6332 #endif
6333 #ifdef SIGKILL
6334 parse_signal ("kill", SIGKILL);
6335 #endif
6336 #ifdef SIGFPE
6337 parse_signal ("fpe", SIGFPE);
6338 #endif
6339 #ifdef SIGBUS
6340 parse_signal ("bus", SIGBUS);
6341 #endif
6342 #ifdef SIGSEGV
6343 parse_signal ("segv", SIGSEGV);
6344 #endif
6345 #ifdef SIGSYS
6346 parse_signal ("sys", SIGSYS);
6347 #endif
6348 #ifdef SIGPIPE
6349 parse_signal ("pipe", SIGPIPE);
6350 #endif
6351 #ifdef SIGALRM
6352 parse_signal ("alrm", SIGALRM);
6353 #endif
6354 #ifdef SIGURG
6355 parse_signal ("urg", SIGURG);
6356 #endif
6357 #ifdef SIGSTOP
6358 parse_signal ("stop", SIGSTOP);
6359 #endif
6360 #ifdef SIGTSTP
6361 parse_signal ("tstp", SIGTSTP);
6362 #endif
6363 #ifdef SIGCONT
6364 parse_signal ("cont", SIGCONT);
6365 #endif
6366 #ifdef SIGCHLD
6367 parse_signal ("chld", SIGCHLD);
6368 #endif
6369 #ifdef SIGTTIN
6370 parse_signal ("ttin", SIGTTIN);
6371 #endif
6372 #ifdef SIGTTOU
6373 parse_signal ("ttou", SIGTTOU);
6374 #endif
6375 #ifdef SIGIO
6376 parse_signal ("io", SIGIO);
6377 #endif
6378 #ifdef SIGXCPU
6379 parse_signal ("xcpu", SIGXCPU);
6380 #endif
6381 #ifdef SIGXFSZ
6382 parse_signal ("xfsz", SIGXFSZ);
6383 #endif
6384 #ifdef SIGVTALRM
6385 parse_signal ("vtalrm", SIGVTALRM);
6386 #endif
6387 #ifdef SIGPROF
6388 parse_signal ("prof", SIGPROF);
6389 #endif
6390 #ifdef SIGWINCH
6391 parse_signal ("winch", SIGWINCH);
6392 #endif
6393 #ifdef SIGINFO
6394 parse_signal ("info", SIGINFO);
6395 #endif
6396 else
6397 error ("Undefined signal name %s", name);
6398 }
6399
6400 #undef parse_signal
6401
6402 return make_number (kill (pid, XINT (sigcode)));
6403 }
6404
6405 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6406 doc: /* Make PROCESS see end-of-file in its input.
6407 EOF comes after any text already sent to it.
6408 PROCESS may be a process, a buffer, the name of a process or buffer, or
6409 nil, indicating the current buffer's process.
6410 If PROCESS is a network connection, or is a process communicating
6411 through a pipe (as opposed to a pty), then you cannot send any more
6412 text to PROCESS after you call this function.
6413 If PROCESS is a serial process, wait until all output written to the
6414 process has been transmitted to the serial port. */)
6415 (process)
6416 Lisp_Object process;
6417 {
6418 Lisp_Object proc;
6419 struct coding_system *coding;
6420
6421 if (DATAGRAM_CONN_P (process))
6422 return process;
6423
6424 proc = get_process (process);
6425 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6426
6427 /* Make sure the process is really alive. */
6428 if (XPROCESS (proc)->raw_status_new)
6429 update_status (XPROCESS (proc));
6430 if (! EQ (XPROCESS (proc)->status, Qrun))
6431 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6432
6433 if (CODING_REQUIRE_FLUSHING (coding))
6434 {
6435 coding->mode |= CODING_MODE_LAST_BLOCK;
6436 send_process (proc, "", 0, Qnil);
6437 }
6438
6439 if (XPROCESS (proc)->pty_flag)
6440 send_process (proc, "\004", 1, Qnil);
6441 else if (EQ (XPROCESS (proc)->type, Qserial))
6442 {
6443 #ifdef HAVE_TERMIOS
6444 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6445 error ("tcdrain() failed: %s", emacs_strerror (errno));
6446 #endif
6447 /* Do nothing on Windows because writes are blocking. */
6448 }
6449 else
6450 {
6451 int old_outfd, new_outfd;
6452
6453 #ifdef HAVE_SHUTDOWN
6454 /* If this is a network connection, or socketpair is used
6455 for communication with the subprocess, call shutdown to cause EOF.
6456 (In some old system, shutdown to socketpair doesn't work.
6457 Then we just can't win.) */
6458 if (EQ (XPROCESS (proc)->type, Qnetwork)
6459 || XPROCESS (proc)->outfd == XPROCESS (proc)->infd)
6460 shutdown (XPROCESS (proc)->outfd, 1);
6461 /* In case of socketpair, outfd == infd, so don't close it. */
6462 if (XPROCESS (proc)->outfd != XPROCESS (proc)->infd)
6463 emacs_close (XPROCESS (proc)->outfd);
6464 #else /* not HAVE_SHUTDOWN */
6465 emacs_close (XPROCESS (proc)->outfd);
6466 #endif /* not HAVE_SHUTDOWN */
6467 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6468 if (new_outfd < 0)
6469 abort ();
6470 old_outfd = XPROCESS (proc)->outfd;
6471
6472 if (!proc_encode_coding_system[new_outfd])
6473 proc_encode_coding_system[new_outfd]
6474 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
6475 bcopy (proc_encode_coding_system[old_outfd],
6476 proc_encode_coding_system[new_outfd],
6477 sizeof (struct coding_system));
6478 bzero (proc_encode_coding_system[old_outfd],
6479 sizeof (struct coding_system));
6480
6481 XPROCESS (proc)->outfd = new_outfd;
6482 }
6483 return process;
6484 }
6485
6486 /* Kill all processes associated with `buffer'.
6487 If `buffer' is nil, kill all processes */
6488
6489 void
6490 kill_buffer_processes (buffer)
6491 Lisp_Object buffer;
6492 {
6493 Lisp_Object tail, proc;
6494
6495 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6496 {
6497 proc = XCDR (XCAR (tail));
6498 if (PROCESSP (proc)
6499 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
6500 {
6501 if (NETCONN_P (proc) || SERIALCONN_P (proc))
6502 Fdelete_process (proc);
6503 else if (XPROCESS (proc)->infd >= 0)
6504 process_send_signal (proc, SIGHUP, Qnil, 1);
6505 }
6506 }
6507 }
6508 \f
6509 /* On receipt of a signal that a child status has changed, loop asking
6510 about children with changed statuses until the system says there
6511 are no more.
6512
6513 All we do is change the status; we do not run sentinels or print
6514 notifications. That is saved for the next time keyboard input is
6515 done, in order to avoid timing errors.
6516
6517 ** WARNING: this can be called during garbage collection.
6518 Therefore, it must not be fooled by the presence of mark bits in
6519 Lisp objects.
6520
6521 ** USG WARNING: Although it is not obvious from the documentation
6522 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6523 signal() before executing at least one wait(), otherwise the
6524 handler will be called again, resulting in an infinite loop. The
6525 relevant portion of the documentation reads "SIGCLD signals will be
6526 queued and the signal-catching function will be continually
6527 reentered until the queue is empty". Invoking signal() causes the
6528 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6529 Inc.
6530
6531 ** Malloc WARNING: This should never call malloc either directly or
6532 indirectly; if it does, that is a bug */
6533
6534 #ifdef SIGCHLD
6535 SIGTYPE
6536 sigchld_handler (signo)
6537 int signo;
6538 {
6539 int old_errno = errno;
6540 Lisp_Object proc;
6541 register struct Lisp_Process *p;
6542 extern EMACS_TIME *input_available_clear_time;
6543
6544 SIGNAL_THREAD_CHECK (signo);
6545
6546 while (1)
6547 {
6548 pid_t pid;
6549 int w;
6550 Lisp_Object tail;
6551
6552 #ifdef WNOHANG
6553 #ifndef WUNTRACED
6554 #define WUNTRACED 0
6555 #endif /* no WUNTRACED */
6556 /* Keep trying to get a status until we get a definitive result. */
6557 do
6558 {
6559 errno = 0;
6560 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
6561 }
6562 while (pid < 0 && errno == EINTR);
6563
6564 if (pid <= 0)
6565 {
6566 /* PID == 0 means no processes found, PID == -1 means a real
6567 failure. We have done all our job, so return. */
6568
6569 /* USG systems forget handlers when they are used;
6570 must reestablish each time */
6571 #if defined (USG) && !defined (POSIX_SIGNALS)
6572 signal (signo, sigchld_handler); /* WARNING - must come after wait3() */
6573 #endif
6574 errno = old_errno;
6575 return;
6576 }
6577 #else
6578 pid = wait (&w);
6579 #endif /* no WNOHANG */
6580
6581 /* Find the process that signaled us, and record its status. */
6582
6583 /* The process can have been deleted by Fdelete_process. */
6584 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6585 {
6586 Lisp_Object xpid = XCAR (tail);
6587 if ((INTEGERP (xpid) && pid == (pid_t) XINT (xpid))
6588 || (FLOATP (xpid) && pid == (pid_t) XFLOAT_DATA (xpid)))
6589 {
6590 XSETCAR (tail, Qnil);
6591 goto sigchld_end_of_loop;
6592 }
6593 }
6594
6595 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6596 p = 0;
6597 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6598 {
6599 proc = XCDR (XCAR (tail));
6600 p = XPROCESS (proc);
6601 if (EQ (p->type, Qreal) && p->pid == pid)
6602 break;
6603 p = 0;
6604 }
6605
6606 /* Look for an asynchronous process whose pid hasn't been filled
6607 in yet. */
6608 if (p == 0)
6609 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6610 {
6611 proc = XCDR (XCAR (tail));
6612 p = XPROCESS (proc);
6613 if (p->pid == -1)
6614 break;
6615 p = 0;
6616 }
6617
6618 /* Change the status of the process that was found. */
6619 if (p != 0)
6620 {
6621 int clear_desc_flag = 0;
6622
6623 p->tick = ++process_tick;
6624 p->raw_status = w;
6625 p->raw_status_new = 1;
6626
6627 /* If process has terminated, stop waiting for its output. */
6628 if ((WIFSIGNALED (w) || WIFEXITED (w))
6629 && p->infd >= 0)
6630 clear_desc_flag = 1;
6631
6632 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
6633 if (clear_desc_flag)
6634 {
6635 FD_CLR (p->infd, &input_wait_mask);
6636 FD_CLR (p->infd, &non_keyboard_wait_mask);
6637 }
6638
6639 /* Tell wait_reading_process_output that it needs to wake up and
6640 look around. */
6641 if (input_available_clear_time)
6642 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6643 }
6644
6645 /* There was no asynchronous process found for that pid: we have
6646 a synchronous process. */
6647 else
6648 {
6649 synch_process_alive = 0;
6650
6651 /* Report the status of the synchronous process. */
6652 if (WIFEXITED (w))
6653 synch_process_retcode = WRETCODE (w);
6654 else if (WIFSIGNALED (w))
6655 synch_process_termsig = WTERMSIG (w);
6656
6657 /* Tell wait_reading_process_output that it needs to wake up and
6658 look around. */
6659 if (input_available_clear_time)
6660 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6661 }
6662
6663 sigchld_end_of_loop:
6664 ;
6665
6666 /* On some systems, we must return right away.
6667 If any more processes want to signal us, we will
6668 get another signal.
6669 Otherwise (on systems that have WNOHANG), loop around
6670 to use up all the processes that have something to tell us. */
6671 #if (defined WINDOWSNT \
6672 || (defined USG && !defined GNU_LINUX \
6673 && !(defined HPUX && defined WNOHANG)))
6674 #if defined (USG) && ! defined (POSIX_SIGNALS)
6675 signal (signo, sigchld_handler);
6676 #endif
6677 errno = old_errno;
6678 return;
6679 #endif /* USG, but not HPUX with WNOHANG */
6680 }
6681 }
6682 #endif /* SIGCHLD */
6683 \f
6684
6685 static Lisp_Object
6686 exec_sentinel_unwind (data)
6687 Lisp_Object data;
6688 {
6689 XPROCESS (XCAR (data))->sentinel = XCDR (data);
6690 return Qnil;
6691 }
6692
6693 static Lisp_Object
6694 exec_sentinel_error_handler (error)
6695 Lisp_Object error;
6696 {
6697 cmd_error_internal (error, "error in process sentinel: ");
6698 Vinhibit_quit = Qt;
6699 update_echo_area ();
6700 Fsleep_for (make_number (2), Qnil);
6701 return Qt;
6702 }
6703
6704 static void
6705 exec_sentinel (proc, reason)
6706 Lisp_Object proc, reason;
6707 {
6708 Lisp_Object sentinel, obuffer, odeactivate, okeymap;
6709 register struct Lisp_Process *p = XPROCESS (proc);
6710 int count = SPECPDL_INDEX ();
6711 int outer_running_asynch_code = running_asynch_code;
6712 int waiting = waiting_for_user_input_p;
6713
6714 if (inhibit_sentinels)
6715 return;
6716
6717 /* No need to gcpro these, because all we do with them later
6718 is test them for EQness, and none of them should be a string. */
6719 odeactivate = Vdeactivate_mark;
6720 XSETBUFFER (obuffer, current_buffer);
6721 okeymap = current_buffer->keymap;
6722
6723 sentinel = p->sentinel;
6724 if (NILP (sentinel))
6725 return;
6726
6727 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6728 assure that it gets restored no matter how the sentinel exits. */
6729 p->sentinel = Qnil;
6730 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
6731 /* Inhibit quit so that random quits don't screw up a running filter. */
6732 specbind (Qinhibit_quit, Qt);
6733 specbind (Qlast_nonmenu_event, Qt);
6734
6735 /* In case we get recursively called,
6736 and we already saved the match data nonrecursively,
6737 save the same match data in safely recursive fashion. */
6738 if (outer_running_asynch_code)
6739 {
6740 Lisp_Object tem;
6741 tem = Fmatch_data (Qnil, Qnil, Qnil);
6742 restore_search_regs ();
6743 record_unwind_save_match_data ();
6744 Fset_match_data (tem, Qt);
6745 }
6746
6747 /* For speed, if a search happens within this code,
6748 save the match data in a special nonrecursive fashion. */
6749 running_asynch_code = 1;
6750
6751 internal_condition_case_1 (read_process_output_call,
6752 Fcons (sentinel,
6753 Fcons (proc, Fcons (reason, Qnil))),
6754 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6755 exec_sentinel_error_handler);
6756
6757 /* If we saved the match data nonrecursively, restore it now. */
6758 restore_search_regs ();
6759 running_asynch_code = outer_running_asynch_code;
6760
6761 Vdeactivate_mark = odeactivate;
6762
6763 /* Restore waiting_for_user_input_p as it was
6764 when we were called, in case the filter clobbered it. */
6765 waiting_for_user_input_p = waiting;
6766
6767 #if 0
6768 if (! EQ (Fcurrent_buffer (), obuffer)
6769 || ! EQ (current_buffer->keymap, okeymap))
6770 #endif
6771 /* But do it only if the caller is actually going to read events.
6772 Otherwise there's no need to make him wake up, and it could
6773 cause trouble (for example it would make sit_for return). */
6774 if (waiting_for_user_input_p == -1)
6775 record_asynch_buffer_change ();
6776
6777 unbind_to (count, Qnil);
6778 }
6779
6780 /* Report all recent events of a change in process status
6781 (either run the sentinel or output a message).
6782 This is usually done while Emacs is waiting for keyboard input
6783 but can be done at other times. */
6784
6785 static void
6786 status_notify (deleting_process)
6787 struct Lisp_Process *deleting_process;
6788 {
6789 register Lisp_Object proc, buffer;
6790 Lisp_Object tail, msg;
6791 struct gcpro gcpro1, gcpro2;
6792
6793 tail = Qnil;
6794 msg = Qnil;
6795 /* We need to gcpro tail; if read_process_output calls a filter
6796 which deletes a process and removes the cons to which tail points
6797 from Vprocess_alist, and then causes a GC, tail is an unprotected
6798 reference. */
6799 GCPRO2 (tail, msg);
6800
6801 /* Set this now, so that if new processes are created by sentinels
6802 that we run, we get called again to handle their status changes. */
6803 update_tick = process_tick;
6804
6805 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6806 {
6807 Lisp_Object symbol;
6808 register struct Lisp_Process *p;
6809
6810 proc = Fcdr (XCAR (tail));
6811 p = XPROCESS (proc);
6812
6813 if (p->tick != p->update_tick)
6814 {
6815 p->update_tick = p->tick;
6816
6817 /* If process is still active, read any output that remains. */
6818 while (! EQ (p->filter, Qt)
6819 && ! EQ (p->status, Qconnect)
6820 && ! EQ (p->status, Qlisten)
6821 /* Network or serial process not stopped: */
6822 && ! EQ (p->command, Qt)
6823 && p->infd >= 0
6824 && p != deleting_process
6825 && read_process_output (proc, p->infd) > 0);
6826
6827 buffer = p->buffer;
6828
6829 /* Get the text to use for the message. */
6830 if (p->raw_status_new)
6831 update_status (p);
6832 msg = status_message (p);
6833
6834 /* If process is terminated, deactivate it or delete it. */
6835 symbol = p->status;
6836 if (CONSP (p->status))
6837 symbol = XCAR (p->status);
6838
6839 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6840 || EQ (symbol, Qclosed))
6841 {
6842 if (delete_exited_processes)
6843 remove_process (proc);
6844 else
6845 deactivate_process (proc);
6846 }
6847
6848 /* The actions above may have further incremented p->tick.
6849 So set p->update_tick again
6850 so that an error in the sentinel will not cause
6851 this code to be run again. */
6852 p->update_tick = p->tick;
6853 /* Now output the message suitably. */
6854 if (!NILP (p->sentinel))
6855 exec_sentinel (proc, msg);
6856 /* Don't bother with a message in the buffer
6857 when a process becomes runnable. */
6858 else if (!EQ (symbol, Qrun) && !NILP (buffer))
6859 {
6860 Lisp_Object ro, tem;
6861 struct buffer *old = current_buffer;
6862 int opoint, opoint_byte;
6863 int before, before_byte;
6864
6865 ro = XBUFFER (buffer)->read_only;
6866
6867 /* Avoid error if buffer is deleted
6868 (probably that's why the process is dead, too) */
6869 if (NILP (XBUFFER (buffer)->name))
6870 continue;
6871 Fset_buffer (buffer);
6872
6873 opoint = PT;
6874 opoint_byte = PT_BYTE;
6875 /* Insert new output into buffer
6876 at the current end-of-output marker,
6877 thus preserving logical ordering of input and output. */
6878 if (XMARKER (p->mark)->buffer)
6879 Fgoto_char (p->mark);
6880 else
6881 SET_PT_BOTH (ZV, ZV_BYTE);
6882
6883 before = PT;
6884 before_byte = PT_BYTE;
6885
6886 tem = current_buffer->read_only;
6887 current_buffer->read_only = Qnil;
6888 insert_string ("\nProcess ");
6889 Finsert (1, &p->name);
6890 insert_string (" ");
6891 Finsert (1, &msg);
6892 current_buffer->read_only = tem;
6893 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6894
6895 if (opoint >= before)
6896 SET_PT_BOTH (opoint + (PT - before),
6897 opoint_byte + (PT_BYTE - before_byte));
6898 else
6899 SET_PT_BOTH (opoint, opoint_byte);
6900
6901 set_buffer_internal (old);
6902 }
6903 }
6904 } /* end for */
6905
6906 update_mode_lines++; /* in case buffers use %s in mode-line-format */
6907 redisplay_preserve_echo_area (13);
6908
6909 UNGCPRO;
6910 }
6911
6912 \f
6913 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6914 Sset_process_coding_system, 1, 3, 0,
6915 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6916 DECODING will be used to decode subprocess output and ENCODING to
6917 encode subprocess input. */)
6918 (process, decoding, encoding)
6919 register Lisp_Object process, decoding, encoding;
6920 {
6921 register struct Lisp_Process *p;
6922
6923 CHECK_PROCESS (process);
6924 p = XPROCESS (process);
6925 if (p->infd < 0)
6926 error ("Input file descriptor of %s closed", SDATA (p->name));
6927 if (p->outfd < 0)
6928 error ("Output file descriptor of %s closed", SDATA (p->name));
6929 Fcheck_coding_system (decoding);
6930 Fcheck_coding_system (encoding);
6931 encoding = coding_inherit_eol_type (encoding, Qnil);
6932 p->decode_coding_system = decoding;
6933 p->encode_coding_system = encoding;
6934 setup_process_coding_systems (process);
6935
6936 return Qnil;
6937 }
6938
6939 DEFUN ("process-coding-system",
6940 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6941 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6942 (process)
6943 register Lisp_Object process;
6944 {
6945 CHECK_PROCESS (process);
6946 return Fcons (XPROCESS (process)->decode_coding_system,
6947 XPROCESS (process)->encode_coding_system);
6948 }
6949
6950 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6951 Sset_process_filter_multibyte, 2, 2, 0,
6952 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6953 If FLAG is non-nil, the filter is given multibyte strings.
6954 If FLAG is nil, the filter is given unibyte strings. In this case,
6955 all character code conversion except for end-of-line conversion is
6956 suppressed. */)
6957 (process, flag)
6958 Lisp_Object process, flag;
6959 {
6960 register struct Lisp_Process *p;
6961
6962 CHECK_PROCESS (process);
6963 p = XPROCESS (process);
6964 if (NILP (flag))
6965 p->decode_coding_system = raw_text_coding_system (p->decode_coding_system);
6966 setup_process_coding_systems (process);
6967
6968 return Qnil;
6969 }
6970
6971 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6972 Sprocess_filter_multibyte_p, 1, 1, 0,
6973 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6974 (process)
6975 Lisp_Object process;
6976 {
6977 register struct Lisp_Process *p;
6978 struct coding_system *coding;
6979
6980 CHECK_PROCESS (process);
6981 p = XPROCESS (process);
6982 coding = proc_decode_coding_system[p->infd];
6983 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6984 }
6985
6986
6987 \f
6988 /* Add DESC to the set of keyboard input descriptors. */
6989
6990 void
6991 add_keyboard_wait_descriptor (desc)
6992 int desc;
6993 {
6994 FD_SET (desc, &input_wait_mask);
6995 FD_SET (desc, &non_process_wait_mask);
6996 if (desc > max_keyboard_desc)
6997 max_keyboard_desc = desc;
6998 }
6999
7000 static int add_gpm_wait_descriptor_called_flag;
7001
7002 void
7003 add_gpm_wait_descriptor (desc)
7004 int desc;
7005 {
7006 if (! add_gpm_wait_descriptor_called_flag)
7007 FD_CLR (0, &input_wait_mask);
7008 add_gpm_wait_descriptor_called_flag = 1;
7009 FD_SET (desc, &input_wait_mask);
7010 FD_SET (desc, &gpm_wait_mask);
7011 if (desc > max_gpm_desc)
7012 max_gpm_desc = desc;
7013 }
7014
7015 /* From now on, do not expect DESC to give keyboard input. */
7016
7017 void
7018 delete_keyboard_wait_descriptor (desc)
7019 int desc;
7020 {
7021 int fd;
7022 int lim = max_keyboard_desc;
7023
7024 FD_CLR (desc, &input_wait_mask);
7025 FD_CLR (desc, &non_process_wait_mask);
7026
7027 if (desc == max_keyboard_desc)
7028 for (fd = 0; fd < lim; fd++)
7029 if (FD_ISSET (fd, &input_wait_mask)
7030 && !FD_ISSET (fd, &non_keyboard_wait_mask)
7031 && !FD_ISSET (fd, &gpm_wait_mask))
7032 max_keyboard_desc = fd;
7033 }
7034
7035 void
7036 delete_gpm_wait_descriptor (desc)
7037 int desc;
7038 {
7039 int fd;
7040 int lim = max_gpm_desc;
7041
7042 FD_CLR (desc, &input_wait_mask);
7043 FD_CLR (desc, &non_process_wait_mask);
7044
7045 if (desc == max_gpm_desc)
7046 for (fd = 0; fd < lim; fd++)
7047 if (FD_ISSET (fd, &input_wait_mask)
7048 && !FD_ISSET (fd, &non_keyboard_wait_mask)
7049 && !FD_ISSET (fd, &non_process_wait_mask))
7050 max_gpm_desc = fd;
7051 }
7052
7053 /* Return nonzero if *MASK has a bit set
7054 that corresponds to one of the keyboard input descriptors. */
7055
7056 static int
7057 keyboard_bit_set (mask)
7058 SELECT_TYPE *mask;
7059 {
7060 int fd;
7061
7062 for (fd = 0; fd <= max_keyboard_desc; fd++)
7063 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
7064 && !FD_ISSET (fd, &non_keyboard_wait_mask))
7065 return 1;
7066
7067 return 0;
7068 }
7069 \f
7070 /* Enumeration of and access to system processes a-la ps(1). */
7071
7072 #if HAVE_PROCFS
7073
7074 /* Process enumeration and access via /proc. */
7075
7076 static Lisp_Object
7077 procfs_list_system_processes ()
7078 {
7079 Lisp_Object procdir, match, proclist, next;
7080 struct gcpro gcpro1, gcpro2;
7081 register Lisp_Object tail;
7082
7083 GCPRO2 (procdir, match);
7084 /* For every process on the system, there's a directory in the
7085 "/proc" pseudo-directory whose name is the numeric ID of that
7086 process. */
7087 procdir = build_string ("/proc");
7088 match = build_string ("[0-9]+");
7089 proclist = directory_files_internal (procdir, Qnil, match, Qt, 0, Qnil);
7090
7091 /* `proclist' gives process IDs as strings. Destructively convert
7092 each string into a number. */
7093 for (tail = proclist; CONSP (tail); tail = next)
7094 {
7095 next = XCDR (tail);
7096 XSETCAR (tail, Fstring_to_number (XCAR (tail), Qnil));
7097 }
7098 UNGCPRO;
7099
7100 /* directory_files_internal returns the files in reverse order; undo
7101 that. */
7102 proclist = Fnreverse (proclist);
7103 return proclist;
7104 }
7105
7106 static void
7107 time_from_jiffies (unsigned long long tval, long hz,
7108 time_t *sec, unsigned *usec)
7109 {
7110 unsigned long long ullsec;
7111
7112 *sec = tval / hz;
7113 ullsec = *sec;
7114 tval -= ullsec * hz;
7115 /* Careful: if HZ > 1 million, then integer division by it yields zero. */
7116 if (hz <= 1000000)
7117 *usec = tval * 1000000 / hz;
7118 else
7119 *usec = tval / (hz / 1000000);
7120 }
7121
7122 static Lisp_Object
7123 ltime_from_jiffies (unsigned long long tval, long hz)
7124 {
7125 time_t sec;
7126 unsigned usec;
7127
7128 time_from_jiffies (tval, hz, &sec, &usec);
7129
7130 return list3 (make_number ((sec >> 16) & 0xffff),
7131 make_number (sec & 0xffff),
7132 make_number (usec));
7133 }
7134
7135 static void
7136 get_up_time (time_t *sec, unsigned *usec)
7137 {
7138 FILE *fup;
7139
7140 *sec = *usec = 0;
7141
7142 BLOCK_INPUT;
7143 fup = fopen ("/proc/uptime", "r");
7144
7145 if (fup)
7146 {
7147 double uptime, idletime;
7148
7149 /* The numbers in /proc/uptime use C-locale decimal point, but
7150 we already set ourselves to the C locale (see `fixup_locale'
7151 in emacs.c). */
7152 if (2 <= fscanf (fup, "%lf %lf", &uptime, &idletime))
7153 {
7154 *sec = uptime;
7155 *usec = (uptime - *sec) * 1000000;
7156 }
7157 fclose (fup);
7158 }
7159 UNBLOCK_INPUT;
7160 }
7161
7162 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
7163 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
7164
7165 static Lisp_Object
7166 procfs_ttyname (rdev)
7167 {
7168 FILE *fdev = NULL;
7169 char name[PATH_MAX];
7170
7171 BLOCK_INPUT;
7172 fdev = fopen ("/proc/tty/drivers", "r");
7173
7174 if (fdev)
7175 {
7176 unsigned major;
7177 unsigned long minor_beg, minor_end;
7178 char minor[25]; /* 2 32-bit numbers + dash */
7179 char *endp;
7180
7181 while (!feof (fdev) && !ferror (fdev))
7182 {
7183 if (3 <= fscanf (fdev, "%*s %s %u %s %*s\n", name, &major, minor)
7184 && major == MAJOR (rdev))
7185 {
7186 minor_beg = strtoul (minor, &endp, 0);
7187 if (*endp == '\0')
7188 minor_end = minor_beg;
7189 else if (*endp == '-')
7190 minor_end = strtoul (endp + 1, &endp, 0);
7191 else
7192 continue;
7193
7194 if (MINOR (rdev) >= minor_beg && MINOR (rdev) <= minor_end)
7195 {
7196 sprintf (name + strlen (name), "%lu", MINOR (rdev));
7197 break;
7198 }
7199 }
7200 }
7201 fclose (fdev);
7202 }
7203 UNBLOCK_INPUT;
7204 return build_string (name);
7205 }
7206
7207 static unsigned long
7208 procfs_get_total_memory (void)
7209 {
7210 FILE *fmem = NULL;
7211 unsigned long retval = 2 * 1024 * 1024; /* default: 2GB */
7212
7213 BLOCK_INPUT;
7214 fmem = fopen ("/proc/meminfo", "r");
7215
7216 if (fmem)
7217 {
7218 unsigned long entry_value;
7219 char entry_name[20]; /* the longest I saw is 13+1 */
7220
7221 while (!feof (fmem) && !ferror (fmem))
7222 {
7223 if (2 <= fscanf (fmem, "%s %lu kB\n", entry_name, &entry_value)
7224 && strcmp (entry_name, "MemTotal:") == 0)
7225 {
7226 retval = entry_value;
7227 break;
7228 }
7229 }
7230 fclose (fmem);
7231 }
7232 UNBLOCK_INPUT;
7233 return retval;
7234 }
7235
7236 static Lisp_Object
7237 procfs_system_process_attributes (pid)
7238 Lisp_Object pid;
7239 {
7240 char procfn[PATH_MAX], fn[PATH_MAX];
7241 struct stat st;
7242 struct passwd *pw;
7243 struct group *gr;
7244 long clocks_per_sec;
7245 char *procfn_end;
7246 char procbuf[1025], *p, *q;
7247 int fd;
7248 ssize_t nread;
7249 const char *cmd;
7250 char *cmdline = NULL;
7251 size_t cmdsize, cmdline_size;
7252 unsigned char c;
7253 int proc_id, ppid, uid, gid, pgrp, sess, tty, tpgid, thcount;
7254 unsigned long long utime, stime, cutime, cstime, start;
7255 long priority, nice, rss;
7256 unsigned long minflt, majflt, cminflt, cmajflt, vsize;
7257 time_t sec;
7258 unsigned usec;
7259 EMACS_TIME tnow, tstart, tboot, telapsed,ttotal;
7260 double pcpu, pmem;
7261 Lisp_Object attrs = Qnil;
7262 Lisp_Object cmd_str, decoded_cmd, tem;
7263 struct gcpro gcpro1, gcpro2;
7264 EMACS_INT uid_eint, gid_eint;
7265
7266 CHECK_NUMBER_OR_FLOAT (pid);
7267 proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
7268 sprintf (procfn, "/proc/%lu", proc_id);
7269 if (stat (procfn, &st) < 0)
7270 return attrs;
7271
7272 GCPRO2 (attrs, decoded_cmd);
7273
7274 /* euid egid */
7275 uid = st.st_uid;
7276 /* Use of EMACS_INT stops GCC whining about limited range of data type. */
7277 uid_eint = uid;
7278 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid_eint)), attrs);
7279 BLOCK_INPUT;
7280 pw = getpwuid (uid);
7281 UNBLOCK_INPUT;
7282 if (pw)
7283 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
7284
7285 gid = st.st_gid;
7286 gid_eint = gid;
7287 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid_eint)), attrs);
7288 BLOCK_INPUT;
7289 gr = getgrgid (gid);
7290 UNBLOCK_INPUT;
7291 if (gr)
7292 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
7293
7294 strcpy (fn, procfn);
7295 procfn_end = fn + strlen (fn);
7296 strcpy (procfn_end, "/stat");
7297 fd = emacs_open (fn, O_RDONLY, 0);
7298 if (fd >= 0 && (nread = emacs_read (fd, procbuf, sizeof(procbuf) - 1)) > 0)
7299 {
7300 procbuf[nread] = '\0';
7301 p = procbuf;
7302
7303 cmd = NULL;
7304 p = strchr (p, '(');
7305 if (p != NULL)
7306 {
7307 q = strrchr (p + 1, ')');
7308 /* comm */
7309 if (q != NULL)
7310 {
7311 cmd = p + 1;
7312 cmdsize = q - cmd;
7313 }
7314 }
7315 if (cmd == NULL)
7316 {
7317 cmd = "???";
7318 cmdsize = 3;
7319 }
7320 /* Command name is encoded in locale-coding-system; decode it. */
7321 cmd_str = make_unibyte_string (cmd, cmdsize);
7322 decoded_cmd = code_convert_string_norecord (cmd_str,
7323 Vlocale_coding_system, 0);
7324 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
7325
7326 if (q)
7327 {
7328 EMACS_INT ppid_eint, pgrp_eint, sess_eint, tpgid_eint, thcount_eint;
7329 p = q + 2;
7330 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt utime stime cutime cstime priority nice thcount . start vsize rss */
7331 sscanf (p, "%c %d %d %d %d %d %*u %lu %lu %lu %lu %Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld",
7332 &c, &ppid, &pgrp, &sess, &tty, &tpgid,
7333 &minflt, &cminflt, &majflt, &cmajflt,
7334 &utime, &stime, &cutime, &cstime,
7335 &priority, &nice, &thcount, &start, &vsize, &rss);
7336 {
7337 char state_str[2];
7338
7339 state_str[0] = c;
7340 state_str[1] = '\0';
7341 tem = build_string (state_str);
7342 attrs = Fcons (Fcons (Qstate, tem), attrs);
7343 }
7344 /* Stops GCC whining about limited range of data type. */
7345 ppid_eint = ppid;
7346 pgrp_eint = pgrp;
7347 sess_eint = sess;
7348 tpgid_eint = tpgid;
7349 thcount_eint = thcount;
7350 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (ppid_eint)), attrs);
7351 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pgrp_eint)), attrs);
7352 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (sess_eint)), attrs);
7353 attrs = Fcons (Fcons (Qttname, procfs_ttyname (tty)), attrs);
7354 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (tpgid_eint)), attrs);
7355 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (minflt)), attrs);
7356 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (majflt)), attrs);
7357 attrs = Fcons (Fcons (Qcminflt, make_fixnum_or_float (cminflt)), attrs);
7358 attrs = Fcons (Fcons (Qcmajflt, make_fixnum_or_float (cmajflt)), attrs);
7359 clocks_per_sec = sysconf (_SC_CLK_TCK);
7360 if (clocks_per_sec < 0)
7361 clocks_per_sec = 100;
7362 attrs = Fcons (Fcons (Qutime,
7363 ltime_from_jiffies (utime, clocks_per_sec)),
7364 attrs);
7365 attrs = Fcons (Fcons (Qstime,
7366 ltime_from_jiffies (stime, clocks_per_sec)),
7367 attrs);
7368 attrs = Fcons (Fcons (Qcutime,
7369 ltime_from_jiffies (cutime, clocks_per_sec)),
7370 attrs);
7371 attrs = Fcons (Fcons (Qcstime,
7372 ltime_from_jiffies (cstime, clocks_per_sec)),
7373 attrs);
7374 attrs = Fcons (Fcons (Qpri, make_number (priority)), attrs);
7375 attrs = Fcons (Fcons (Qnice, make_number (nice)), attrs);
7376 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (thcount_eint)), attrs);
7377 EMACS_GET_TIME (tnow);
7378 get_up_time (&sec, &usec);
7379 EMACS_SET_SECS (telapsed, sec);
7380 EMACS_SET_USECS (telapsed, usec);
7381 EMACS_SUB_TIME (tboot, tnow, telapsed);
7382 time_from_jiffies (start, clocks_per_sec, &sec, &usec);
7383 EMACS_SET_SECS (tstart, sec);
7384 EMACS_SET_USECS (tstart, usec);
7385 EMACS_ADD_TIME (tstart, tboot, tstart);
7386 attrs = Fcons (Fcons (Qstart,
7387 list3 (make_number
7388 ((EMACS_SECS (tstart) >> 16) & 0xffff),
7389 make_number
7390 (EMACS_SECS (tstart) & 0xffff),
7391 make_number
7392 (EMACS_USECS (tstart)))),
7393 attrs);
7394 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (vsize/1024)), attrs);
7395 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (4*rss)), attrs);
7396 EMACS_SUB_TIME (telapsed, tnow, tstart);
7397 attrs = Fcons (Fcons (Qetime,
7398 list3 (make_number
7399 ((EMACS_SECS (telapsed) >> 16) & 0xffff),
7400 make_number
7401 (EMACS_SECS (telapsed) & 0xffff),
7402 make_number
7403 (EMACS_USECS (telapsed)))),
7404 attrs);
7405 time_from_jiffies (utime + stime, clocks_per_sec, &sec, &usec);
7406 pcpu = (sec + usec / 1000000.0) / (EMACS_SECS (telapsed) + EMACS_USECS (telapsed) / 1000000.0);
7407 attrs = Fcons (Fcons (Qpcpu, make_float (pcpu)), attrs);
7408 pmem = 4.0 * 100 * rss / procfs_get_total_memory ();
7409 if (pmem > 100)
7410 pmem = 100;
7411 attrs = Fcons (Fcons (Qpmem, make_float (pmem)), attrs);
7412 }
7413 }
7414 if (fd >= 0)
7415 emacs_close (fd);
7416
7417 /* args */
7418 strcpy (procfn_end, "/cmdline");
7419 fd = emacs_open (fn, O_RDONLY, 0);
7420 if (fd >= 0)
7421 {
7422 for (cmdline_size = 0; emacs_read (fd, &c, 1) == 1; cmdline_size++)
7423 {
7424 if (isspace (c) || c == '\\')
7425 cmdline_size++; /* for later quoting, see below */
7426 }
7427 if (cmdline_size)
7428 {
7429 cmdline = xmalloc (cmdline_size + 1);
7430 lseek (fd, 0L, SEEK_SET);
7431 cmdline[0] = '\0';
7432 if ((nread = read (fd, cmdline, cmdline_size)) >= 0)
7433 cmdline[nread++] = '\0';
7434 /* We don't want trailing null characters. */
7435 for (p = cmdline + nread - 1; p > cmdline && !*p; p--)
7436 nread--;
7437 for (p = cmdline; p < cmdline + nread; p++)
7438 {
7439 /* Escape-quote whitespace and backslashes. */
7440 if (isspace (*p) || *p == '\\')
7441 {
7442 memmove (p + 1, p, nread - (p - cmdline));
7443 nread++;
7444 *p++ = '\\';
7445 }
7446 else if (*p == '\0')
7447 *p = ' ';
7448 }
7449 cmdline_size = nread;
7450 }
7451 else
7452 {
7453 cmdline_size = cmdsize + 2;
7454 cmdline = xmalloc (cmdline_size + 1);
7455 strcpy (cmdline, "[");
7456 strcat (strncat (cmdline, cmd, cmdsize), "]");
7457 }
7458 emacs_close (fd);
7459 /* Command line is encoded in locale-coding-system; decode it. */
7460 cmd_str = make_unibyte_string (cmdline, cmdline_size);
7461 decoded_cmd = code_convert_string_norecord (cmd_str,
7462 Vlocale_coding_system, 0);
7463 xfree (cmdline);
7464 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
7465 }
7466
7467 UNGCPRO;
7468 return attrs;
7469 }
7470
7471 #endif /* !HAVE_PROCFS */
7472
7473 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7474 0, 0, 0,
7475 doc: /* Return a list of numerical process IDs of all running processes.
7476 If this functionality is unsupported, return nil.
7477
7478 See `system-process-attributes' for getting attributes of a process
7479 given its ID. */)
7480 ()
7481 {
7482 #ifdef LISTPROC
7483 return LISTPROC ();
7484 #else
7485 return Qnil;
7486 #endif
7487 }
7488
7489 DEFUN ("system-process-attributes", Fsystem_process_attributes,
7490 Ssystem_process_attributeses, 1, 1, 0,
7491 doc: /* Return attributes of the process given by its PID, a number.
7492
7493 Value is an alist where each element is a cons cell of the form
7494
7495 \(KEY . VALUE)
7496
7497 If this functionality is unsupported, the value is nil.
7498
7499 See `list-system-processes' for getting a list of all process IDs.
7500
7501 The KEYs of the attributes that this function may return are listed
7502 below, together with the type of the associated VALUE (in parentheses).
7503 Not all platforms support all of these attributes; unsupported
7504 attributes will not appear in the returned alist.
7505 Unless explicitly indicated otherwise, numbers can have either
7506 integer or floating point values.
7507
7508 euid -- Effective user User ID of the process (number)
7509 user -- User name corresponding to euid (string)
7510 egid -- Effective user Group ID of the process (number)
7511 group -- Group name corresponding to egid (string)
7512 comm -- Command name (executable name only) (string)
7513 state -- Process state code, such as "S", "R", or "T" (string)
7514 ppid -- Parent process ID (number)
7515 pgrp -- Process group ID (number)
7516 sess -- Session ID, i.e. process ID of session leader (number)
7517 ttname -- Controlling tty name (string)
7518 tpgid -- ID of foreground process group on the process's tty (number)
7519 minflt -- number of minor page faults (number)
7520 majflt -- number of major page faults (number)
7521 cminflt -- cumulative number of minor page faults (number)
7522 cmajflt -- cumulative number of major page faults (number)
7523 utime -- user time used by the process, in the (HIGH LOW USEC) format
7524 stime -- system time used by the process, in the (HIGH LOW USEC) format
7525 cutime -- user time used by the process and its children, (HIGH LOW USEC)
7526 cstime -- system time used by the process and its children, (HIGH LOW USEC)
7527 pri -- priority of the process (number)
7528 nice -- nice value of the process (number)
7529 thcount -- process thread count (number)
7530 start -- time the process started, in the (HIGH LOW USEC) format
7531 vsize -- virtual memory size of the process in KB's (number)
7532 rss -- resident set size of the process in KB's (number)
7533 etime -- elapsed time the process is running, in (HIGH LOW USEC) format
7534 pcpu -- percents of CPU time used by the process (floating-point number)
7535 pmem -- percents of total physical memory used by process's resident set
7536 (floating-point number)
7537 args -- command line which invoked the process (string). */)
7538 (pid)
7539
7540 Lisp_Object pid;
7541 {
7542 #ifdef PROCATTR
7543 return PROCATTR (pid);
7544 #else
7545 return Qnil;
7546 #endif
7547 }
7548 \f
7549 void
7550 init_process ()
7551 {
7552 register int i;
7553
7554 inhibit_sentinels = 0;
7555
7556 #ifdef SIGCHLD
7557 #ifndef CANNOT_DUMP
7558 if (! noninteractive || initialized)
7559 #endif
7560 signal (SIGCHLD, sigchld_handler);
7561 #endif
7562
7563 FD_ZERO (&input_wait_mask);
7564 FD_ZERO (&non_keyboard_wait_mask);
7565 FD_ZERO (&non_process_wait_mask);
7566 max_process_desc = 0;
7567
7568 #ifdef NON_BLOCKING_CONNECT
7569 FD_ZERO (&connect_wait_mask);
7570 num_pending_connects = 0;
7571 #endif
7572
7573 #ifdef ADAPTIVE_READ_BUFFERING
7574 process_output_delay_count = 0;
7575 process_output_skip = 0;
7576 #endif
7577
7578 /* Don't do this, it caused infinite select loops. The display
7579 method should call add_keyboard_wait_descriptor on stdin if it
7580 needs that. */
7581 #if 0
7582 FD_SET (0, &input_wait_mask);
7583 #endif
7584
7585 Vprocess_alist = Qnil;
7586 #ifdef SIGCHLD
7587 deleted_pid_list = Qnil;
7588 #endif
7589 for (i = 0; i < MAXDESC; i++)
7590 {
7591 chan_process[i] = Qnil;
7592 proc_buffered_char[i] = -1;
7593 }
7594 bzero (proc_decode_coding_system, sizeof proc_decode_coding_system);
7595 bzero (proc_encode_coding_system, sizeof proc_encode_coding_system);
7596 #ifdef DATAGRAM_SOCKETS
7597 bzero (datagram_address, sizeof datagram_address);
7598 #endif
7599
7600 #ifdef HAVE_SOCKETS
7601 {
7602 Lisp_Object subfeatures = Qnil;
7603 struct socket_options *sopt;
7604
7605 #define ADD_SUBFEATURE(key, val) \
7606 subfeatures = Fcons (Fcons (key, Fcons (val, Qnil)), subfeatures)
7607
7608 #ifdef NON_BLOCKING_CONNECT
7609 ADD_SUBFEATURE (QCnowait, Qt);
7610 #endif
7611 #ifdef DATAGRAM_SOCKETS
7612 ADD_SUBFEATURE (QCtype, Qdatagram);
7613 #endif
7614 #ifdef HAVE_LOCAL_SOCKETS
7615 ADD_SUBFEATURE (QCfamily, Qlocal);
7616 #endif
7617 ADD_SUBFEATURE (QCfamily, Qipv4);
7618 #ifdef AF_INET6
7619 ADD_SUBFEATURE (QCfamily, Qipv6);
7620 #endif
7621 #ifdef HAVE_GETSOCKNAME
7622 ADD_SUBFEATURE (QCservice, Qt);
7623 #endif
7624 #if defined(O_NONBLOCK) || defined(O_NDELAY)
7625 ADD_SUBFEATURE (QCserver, Qt);
7626 #endif
7627
7628 for (sopt = socket_options; sopt->name; sopt++)
7629 subfeatures = Fcons (intern (sopt->name), subfeatures);
7630
7631 Fprovide (intern ("make-network-process"), subfeatures);
7632 }
7633 #endif /* HAVE_SOCKETS */
7634
7635 #if defined (DARWIN_OS)
7636 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7637 processes. As such, we only change the default value. */
7638 if (initialized)
7639 {
7640 char *release = get_operating_system_release();
7641 if (!release || !release[0] || (release[0] < MIN_PTY_KERNEL_VERSION
7642 && release[1] == '.')) {
7643 Vprocess_connection_type = Qnil;
7644 }
7645 }
7646 #endif
7647 }
7648
7649 void
7650 syms_of_process ()
7651 {
7652 Qprocessp = intern ("processp");
7653 staticpro (&Qprocessp);
7654 Qrun = intern ("run");
7655 staticpro (&Qrun);
7656 Qstop = intern ("stop");
7657 staticpro (&Qstop);
7658 Qsignal = intern ("signal");
7659 staticpro (&Qsignal);
7660
7661 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7662 here again.
7663
7664 Qexit = intern ("exit");
7665 staticpro (&Qexit); */
7666
7667 Qopen = intern ("open");
7668 staticpro (&Qopen);
7669 Qclosed = intern ("closed");
7670 staticpro (&Qclosed);
7671 Qconnect = intern ("connect");
7672 staticpro (&Qconnect);
7673 Qfailed = intern ("failed");
7674 staticpro (&Qfailed);
7675 Qlisten = intern ("listen");
7676 staticpro (&Qlisten);
7677 Qlocal = intern ("local");
7678 staticpro (&Qlocal);
7679 Qipv4 = intern ("ipv4");
7680 staticpro (&Qipv4);
7681 #ifdef AF_INET6
7682 Qipv6 = intern ("ipv6");
7683 staticpro (&Qipv6);
7684 #endif
7685 Qdatagram = intern ("datagram");
7686 staticpro (&Qdatagram);
7687
7688 QCport = intern (":port");
7689 staticpro (&QCport);
7690 QCspeed = intern (":speed");
7691 staticpro (&QCspeed);
7692 QCprocess = intern (":process");
7693 staticpro (&QCprocess);
7694
7695 QCbytesize = intern (":bytesize");
7696 staticpro (&QCbytesize);
7697 QCstopbits = intern (":stopbits");
7698 staticpro (&QCstopbits);
7699 QCparity = intern (":parity");
7700 staticpro (&QCparity);
7701 Qodd = intern ("odd");
7702 staticpro (&Qodd);
7703 Qeven = intern ("even");
7704 staticpro (&Qeven);
7705 QCflowcontrol = intern (":flowcontrol");
7706 staticpro (&QCflowcontrol);
7707 Qhw = intern ("hw");
7708 staticpro (&Qhw);
7709 Qsw = intern ("sw");
7710 staticpro (&Qsw);
7711 QCsummary = intern (":summary");
7712 staticpro (&QCsummary);
7713
7714 Qreal = intern ("real");
7715 staticpro (&Qreal);
7716 Qnetwork = intern ("network");
7717 staticpro (&Qnetwork);
7718 Qserial = intern ("serial");
7719 staticpro (&Qserial);
7720
7721 QCname = intern (":name");
7722 staticpro (&QCname);
7723 QCbuffer = intern (":buffer");
7724 staticpro (&QCbuffer);
7725 QChost = intern (":host");
7726 staticpro (&QChost);
7727 QCservice = intern (":service");
7728 staticpro (&QCservice);
7729 QCtype = intern (":type");
7730 staticpro (&QCtype);
7731 QClocal = intern (":local");
7732 staticpro (&QClocal);
7733 QCremote = intern (":remote");
7734 staticpro (&QCremote);
7735 QCcoding = intern (":coding");
7736 staticpro (&QCcoding);
7737 QCserver = intern (":server");
7738 staticpro (&QCserver);
7739 QCnowait = intern (":nowait");
7740 staticpro (&QCnowait);
7741 QCsentinel = intern (":sentinel");
7742 staticpro (&QCsentinel);
7743 QClog = intern (":log");
7744 staticpro (&QClog);
7745 QCnoquery = intern (":noquery");
7746 staticpro (&QCnoquery);
7747 QCstop = intern (":stop");
7748 staticpro (&QCstop);
7749 QCoptions = intern (":options");
7750 staticpro (&QCoptions);
7751 QCplist = intern (":plist");
7752 staticpro (&QCplist);
7753
7754 Qlast_nonmenu_event = intern ("last-nonmenu-event");
7755 staticpro (&Qlast_nonmenu_event);
7756
7757 staticpro (&Vprocess_alist);
7758 #ifdef SIGCHLD
7759 staticpro (&deleted_pid_list);
7760 #endif
7761
7762 Qeuid = intern ("euid");
7763 staticpro (&Qeuid);
7764 Qegid = intern ("egid");
7765 staticpro (&Qegid);
7766 Quser = intern ("user");
7767 staticpro (&Quser);
7768 Qgroup = intern ("group");
7769 staticpro (&Qgroup);
7770 Qcomm = intern ("comm");
7771 staticpro (&Qcomm);
7772 Qstate = intern ("state");
7773 staticpro (&Qstate);
7774 Qppid = intern ("ppid");
7775 staticpro (&Qppid);
7776 Qpgrp = intern ("pgrp");
7777 staticpro (&Qpgrp);
7778 Qsess = intern ("sess");
7779 staticpro (&Qsess);
7780 Qttname = intern ("ttname");
7781 staticpro (&Qttname);
7782 Qtpgid = intern ("tpgid");
7783 staticpro (&Qtpgid);
7784 Qminflt = intern ("minflt");
7785 staticpro (&Qminflt);
7786 Qmajflt = intern ("majflt");
7787 staticpro (&Qmajflt);
7788 Qcminflt = intern ("cminflt");
7789 staticpro (&Qcminflt);
7790 Qcmajflt = intern ("cmajflt");
7791 staticpro (&Qcmajflt);
7792 Qutime = intern ("utime");
7793 staticpro (&Qutime);
7794 Qstime = intern ("stime");
7795 staticpro (&Qstime);
7796 Qcutime = intern ("cutime");
7797 staticpro (&Qcutime);
7798 Qcstime = intern ("cstime");
7799 staticpro (&Qcstime);
7800 Qpri = intern ("pri");
7801 staticpro (&Qpri);
7802 Qnice = intern ("nice");
7803 staticpro (&Qnice);
7804 Qthcount = intern ("thcount");
7805 staticpro (&Qthcount);
7806 Qstart = intern ("start");
7807 staticpro (&Qstart);
7808 Qvsize = intern ("vsize");
7809 staticpro (&Qvsize);
7810 Qrss = intern ("rss");
7811 staticpro (&Qrss);
7812 Qetime = intern ("etime");
7813 staticpro (&Qetime);
7814 Qpcpu = intern ("pcpu");
7815 staticpro (&Qpcpu);
7816 Qpmem = intern ("pmem");
7817 staticpro (&Qpmem);
7818 Qargs = intern ("args");
7819 staticpro (&Qargs);
7820
7821 DEFVAR_BOOL ("delete-exited-processes", &delete_exited_processes,
7822 doc: /* *Non-nil means delete processes immediately when they exit.
7823 A value of nil means don't delete them until `list-processes' is run. */);
7824
7825 delete_exited_processes = 1;
7826
7827 DEFVAR_LISP ("process-connection-type", &Vprocess_connection_type,
7828 doc: /* Control type of device used to communicate with subprocesses.
7829 Values are nil to use a pipe, or t or `pty' to use a pty.
7830 The value has no effect if the system has no ptys or if all ptys are busy:
7831 then a pipe is used in any case.
7832 The value takes effect when `start-process' is called. */);
7833 Vprocess_connection_type = Qt;
7834
7835 #ifdef ADAPTIVE_READ_BUFFERING
7836 DEFVAR_LISP ("process-adaptive-read-buffering", &Vprocess_adaptive_read_buffering,
7837 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7838 On some systems, when Emacs reads the output from a subprocess, the output data
7839 is read in very small blocks, potentially resulting in very poor performance.
7840 This behavior can be remedied to some extent by setting this variable to a
7841 non-nil value, as it will automatically delay reading from such processes, to
7842 allow them to produce more output before Emacs tries to read it.
7843 If the value is t, the delay is reset after each write to the process; any other
7844 non-nil value means that the delay is not reset on write.
7845 The variable takes effect when `start-process' is called. */);
7846 Vprocess_adaptive_read_buffering = Qt;
7847 #endif
7848
7849 defsubr (&Sprocessp);
7850 defsubr (&Sget_process);
7851 defsubr (&Sget_buffer_process);
7852 defsubr (&Sdelete_process);
7853 defsubr (&Sprocess_status);
7854 defsubr (&Sprocess_exit_status);
7855 defsubr (&Sprocess_id);
7856 defsubr (&Sprocess_name);
7857 defsubr (&Sprocess_tty_name);
7858 defsubr (&Sprocess_command);
7859 defsubr (&Sset_process_buffer);
7860 defsubr (&Sprocess_buffer);
7861 defsubr (&Sprocess_mark);
7862 defsubr (&Sset_process_filter);
7863 defsubr (&Sprocess_filter);
7864 defsubr (&Sset_process_sentinel);
7865 defsubr (&Sprocess_sentinel);
7866 defsubr (&Sset_process_window_size);
7867 defsubr (&Sset_process_inherit_coding_system_flag);
7868 defsubr (&Sprocess_inherit_coding_system_flag);
7869 defsubr (&Sset_process_query_on_exit_flag);
7870 defsubr (&Sprocess_query_on_exit_flag);
7871 defsubr (&Sprocess_contact);
7872 defsubr (&Sprocess_plist);
7873 defsubr (&Sset_process_plist);
7874 defsubr (&Slist_processes);
7875 defsubr (&Sprocess_list);
7876 defsubr (&Sstart_process);
7877 #ifdef HAVE_SERIAL
7878 defsubr (&Sserial_process_configure);
7879 defsubr (&Smake_serial_process);
7880 #endif /* HAVE_SERIAL */
7881 #ifdef HAVE_SOCKETS
7882 defsubr (&Sset_network_process_option);
7883 defsubr (&Smake_network_process);
7884 defsubr (&Sformat_network_address);
7885 #endif /* HAVE_SOCKETS */
7886 #if defined(HAVE_SOCKETS) && defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
7887 #ifdef SIOCGIFCONF
7888 defsubr (&Snetwork_interface_list);
7889 #endif
7890 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
7891 defsubr (&Snetwork_interface_info);
7892 #endif
7893 #endif /* HAVE_SOCKETS ... */
7894 #ifdef DATAGRAM_SOCKETS
7895 defsubr (&Sprocess_datagram_address);
7896 defsubr (&Sset_process_datagram_address);
7897 #endif
7898 defsubr (&Saccept_process_output);
7899 defsubr (&Sprocess_send_region);
7900 defsubr (&Sprocess_send_string);
7901 defsubr (&Sinterrupt_process);
7902 defsubr (&Skill_process);
7903 defsubr (&Squit_process);
7904 defsubr (&Sstop_process);
7905 defsubr (&Scontinue_process);
7906 defsubr (&Sprocess_running_child_p);
7907 defsubr (&Sprocess_send_eof);
7908 defsubr (&Ssignal_process);
7909 defsubr (&Swaiting_for_user_input_p);
7910 defsubr (&Sprocess_type);
7911 defsubr (&Sset_process_coding_system);
7912 defsubr (&Sprocess_coding_system);
7913 defsubr (&Sset_process_filter_multibyte);
7914 defsubr (&Sprocess_filter_multibyte_p);
7915 defsubr (&Slist_system_processes);
7916 defsubr (&Ssystem_process_attributeses);
7917 }
7918
7919 \f
7920 #else /* not subprocesses */
7921
7922 #include <sys/types.h>
7923 #include <errno.h>
7924 #include <sys/stat.h>
7925 #include <stdlib.h>
7926 #include <fcntl.h>
7927 #ifdef HAVE_UNISTD_H
7928 #include <unistd.h>
7929 #endif
7930
7931 #include "lisp.h"
7932 #include "systime.h"
7933 #include "character.h"
7934 #include "coding.h"
7935 #include "termopts.h"
7936 #include "sysselect.h"
7937
7938 extern int frame_garbaged;
7939
7940 extern EMACS_TIME timer_check ();
7941 extern int timers_run;
7942
7943 Lisp_Object QCtype, QCname;
7944
7945 /* As described above, except assuming that there are no subprocesses:
7946
7947 Wait for timeout to elapse and/or keyboard input to be available.
7948
7949 time_limit is:
7950 timeout in seconds, or
7951 zero for no limit, or
7952 -1 means gobble data immediately available but don't wait for any.
7953
7954 read_kbd is a Lisp_Object:
7955 0 to ignore keyboard input, or
7956 1 to return when input is available, or
7957 -1 means caller will actually read the input, so don't throw to
7958 the quit handler.
7959
7960 see full version for other parameters. We know that wait_proc will
7961 always be NULL, since `subprocesses' isn't defined.
7962
7963 do_display != 0 means redisplay should be done to show subprocess
7964 output that arrives.
7965
7966 Return true if we received input from any process. */
7967
7968 int
7969 wait_reading_process_output (time_limit, microsecs, read_kbd, do_display,
7970 wait_for_cell, wait_proc, just_wait_proc)
7971 int time_limit, microsecs, read_kbd, do_display;
7972 Lisp_Object wait_for_cell;
7973 struct Lisp_Process *wait_proc;
7974 int just_wait_proc;
7975 {
7976 register int nfds;
7977 EMACS_TIME end_time, timeout;
7978 SELECT_TYPE waitchannels;
7979 int xerrno;
7980
7981 /* What does time_limit really mean? */
7982 if (time_limit || microsecs)
7983 {
7984 EMACS_GET_TIME (end_time);
7985 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
7986 EMACS_ADD_TIME (end_time, end_time, timeout);
7987 }
7988
7989 /* Turn off periodic alarms (in case they are in use)
7990 and then turn off any other atimers,
7991 because the select emulator uses alarms. */
7992 stop_polling ();
7993 turn_on_atimers (0);
7994
7995 while (1)
7996 {
7997 int timeout_reduced_for_timers = 0;
7998
7999 /* If calling from keyboard input, do not quit
8000 since we want to return C-g as an input character.
8001 Otherwise, do pending quit if requested. */
8002 if (read_kbd >= 0)
8003 QUIT;
8004
8005 /* Exit now if the cell we're waiting for became non-nil. */
8006 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
8007 break;
8008
8009 /* Compute time from now till when time limit is up */
8010 /* Exit if already run out */
8011 if (time_limit == -1)
8012 {
8013 /* -1 specified for timeout means
8014 gobble output available now
8015 but don't wait at all. */
8016
8017 EMACS_SET_SECS_USECS (timeout, 0, 0);
8018 }
8019 else if (time_limit || microsecs)
8020 {
8021 EMACS_GET_TIME (timeout);
8022 EMACS_SUB_TIME (timeout, end_time, timeout);
8023 if (EMACS_TIME_NEG_P (timeout))
8024 break;
8025 }
8026 else
8027 {
8028 EMACS_SET_SECS_USECS (timeout, 100000, 0);
8029 }
8030
8031 /* If our caller will not immediately handle keyboard events,
8032 run timer events directly.
8033 (Callers that will immediately read keyboard events
8034 call timer_delay on their own.) */
8035 if (NILP (wait_for_cell))
8036 {
8037 EMACS_TIME timer_delay;
8038
8039 do
8040 {
8041 int old_timers_run = timers_run;
8042 timer_delay = timer_check (1);
8043 if (timers_run != old_timers_run && do_display)
8044 /* We must retry, since a timer may have requeued itself
8045 and that could alter the time delay. */
8046 redisplay_preserve_echo_area (14);
8047 else
8048 break;
8049 }
8050 while (!detect_input_pending ());
8051
8052 /* If there is unread keyboard input, also return. */
8053 if (read_kbd != 0
8054 && requeued_events_pending_p ())
8055 break;
8056
8057 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
8058 {
8059 EMACS_TIME difference;
8060 EMACS_SUB_TIME (difference, timer_delay, timeout);
8061 if (EMACS_TIME_NEG_P (difference))
8062 {
8063 timeout = timer_delay;
8064 timeout_reduced_for_timers = 1;
8065 }
8066 }
8067 }
8068
8069 /* Cause C-g and alarm signals to take immediate action,
8070 and cause input available signals to zero out timeout. */
8071 if (read_kbd < 0)
8072 set_waiting_for_input (&timeout);
8073
8074 /* Wait till there is something to do. */
8075
8076 if (! read_kbd && NILP (wait_for_cell))
8077 FD_ZERO (&waitchannels);
8078 else
8079 FD_SET (0, &waitchannels);
8080
8081 /* If a frame has been newly mapped and needs updating,
8082 reprocess its display stuff. */
8083 if (frame_garbaged && do_display)
8084 {
8085 clear_waiting_for_input ();
8086 redisplay_preserve_echo_area (15);
8087 if (read_kbd < 0)
8088 set_waiting_for_input (&timeout);
8089 }
8090
8091 if (read_kbd && detect_input_pending ())
8092 {
8093 nfds = 0;
8094 FD_ZERO (&waitchannels);
8095 }
8096 else
8097 nfds = select (1, &waitchannels, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
8098 &timeout);
8099
8100 xerrno = errno;
8101
8102 /* Make C-g and alarm signals set flags again */
8103 clear_waiting_for_input ();
8104
8105 /* If we woke up due to SIGWINCH, actually change size now. */
8106 do_pending_window_change (0);
8107
8108 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
8109 /* We waited the full specified time, so return now. */
8110 break;
8111
8112 if (nfds == -1)
8113 {
8114 /* If the system call was interrupted, then go around the
8115 loop again. */
8116 if (xerrno == EINTR)
8117 FD_ZERO (&waitchannels);
8118 else
8119 error ("select error: %s", emacs_strerror (xerrno));
8120 }
8121 #ifdef SOLARIS2
8122 else if (nfds > 0 && (waitchannels & 1) && interrupt_input)
8123 /* System sometimes fails to deliver SIGIO. */
8124 kill (getpid (), SIGIO);
8125 #endif
8126 #ifdef SIGIO
8127 if (read_kbd && interrupt_input && (waitchannels & 1))
8128 kill (getpid (), SIGIO);
8129 #endif
8130
8131 /* Check for keyboard input */
8132
8133 if (read_kbd
8134 && detect_input_pending_run_timers (do_display))
8135 {
8136 swallow_events (do_display);
8137 if (detect_input_pending_run_timers (do_display))
8138 break;
8139 }
8140
8141 /* If there is unread keyboard input, also return. */
8142 if (read_kbd
8143 && requeued_events_pending_p ())
8144 break;
8145
8146 /* If wait_for_cell. check for keyboard input
8147 but don't run any timers.
8148 ??? (It seems wrong to me to check for keyboard
8149 input at all when wait_for_cell, but the code
8150 has been this way since July 1994.
8151 Try changing this after version 19.31.) */
8152 if (! NILP (wait_for_cell)
8153 && detect_input_pending ())
8154 {
8155 swallow_events (do_display);
8156 if (detect_input_pending ())
8157 break;
8158 }
8159
8160 /* Exit now if the cell we're waiting for became non-nil. */
8161 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
8162 break;
8163 }
8164
8165 start_polling ();
8166
8167 return 0;
8168 }
8169
8170
8171 /* Don't confuse make-docfile by having two doc strings for this function.
8172 make-docfile does not pay attention to #if, for good reason! */
8173 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
8174 0)
8175 (name)
8176 register Lisp_Object name;
8177 {
8178 return Qnil;
8179 }
8180
8181 /* Don't confuse make-docfile by having two doc strings for this function.
8182 make-docfile does not pay attention to #if, for good reason! */
8183 DEFUN ("process-inherit-coding-system-flag",
8184 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
8185 1, 1, 0,
8186 0)
8187 (process)
8188 register Lisp_Object process;
8189 {
8190 /* Ignore the argument and return the value of
8191 inherit-process-coding-system. */
8192 return inherit_process_coding_system ? Qt : Qnil;
8193 }
8194
8195 /* Kill all processes associated with `buffer'.
8196 If `buffer' is nil, kill all processes.
8197 Since we have no subprocesses, this does nothing. */
8198
8199 void
8200 kill_buffer_processes (buffer)
8201 Lisp_Object buffer;
8202 {
8203 }
8204
8205 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
8206 0, 0, 0,
8207 doc: /* Return a list of numerical process IDs of all running processes.
8208 If this functionality is unsupported, return nil.
8209
8210 See `system-process-attributes' for getting attributes of a process
8211 given its ID. */)
8212 ()
8213 {
8214 return Qnil;
8215 }
8216
8217 DEFUN ("system-process-attributes", Fsystem_process_attributes,
8218 Ssystem_process_attributeses, 1, 1, 0,
8219 doc: /* Return attributes of the process given by its PID, a number.
8220
8221 Value is an alist where each element is a cons cell of the form
8222
8223 \(KEY . VALUE)
8224
8225 If this functionality is unsupported, the value is nil.
8226
8227 See `list-system-processes' for getting a list of all process IDs.
8228
8229 The KEYs of the attributes that this function may return are listed
8230 below, together with the type of the associated VALUE (in parentheses).
8231 Not all platforms support all of these attributes; unsupported
8232 attributes will not appear in the returned alist.
8233 Unless explicitly indicated otherwise, numbers can have either
8234 integer or floating point values.
8235
8236 euid -- Effective user User ID of the process (number)
8237 user -- User name corresponding to euid (string)
8238 egid -- Effective user Group ID of the process (number)
8239 group -- Group name corresponding to egid (string)
8240 comm -- Command name (executable name only) (string)
8241 state -- Process state code, such as "S", "R", or "T" (string)
8242 ppid -- Parent process ID (number)
8243 pgrp -- Process group ID (number)
8244 sess -- Session ID, i.e. process ID of session leader (number)
8245 ttname -- Controlling tty name (string)
8246 tpgid -- ID of foreground process group on the process's tty (number)
8247 minflt -- number of minor page faults (number)
8248 majflt -- number of major page faults (number)
8249 cminflt -- cumulative number of minor page faults (number)
8250 cmajflt -- cumulative number of major page faults (number)
8251 utime -- user time used by the process, in the (HIGH LOW USEC) format
8252 stime -- system time used by the process, in the (HIGH LOW USEC) format
8253 cutime -- user time used by the process and its children, (HIGH LOW USEC)
8254 cstime -- system time used by the process and its children, (HIGH LOW USEC)
8255 pri -- priority of the process (number)
8256 nice -- nice value of the process (number)
8257 thcount -- process thread count (number)
8258 start -- time the process started, in the (HIGH LOW USEC) format
8259 vsize -- virtual memory size of the process in KB's (number)
8260 rss -- resident set size of the process in KB's (number)
8261 etime -- elapsed time the process is running, in (HIGH LOW USEC) format
8262 pcpu -- percents of CPU time used by the process (floating-point number)
8263 pmem -- percents of total physical memory used by process's resident set
8264 (floating-point number)
8265 args -- command line which invoked the process (string). */)
8266 (pid)
8267
8268 Lisp_Object pid;
8269 {
8270 return Qnil;
8271 }
8272
8273 void
8274 init_process ()
8275 {
8276 }
8277
8278 void
8279 syms_of_process ()
8280 {
8281 QCtype = intern (":type");
8282 staticpro (&QCtype);
8283 QCname = intern (":name");
8284 staticpro (&QCname);
8285
8286 defsubr (&Sget_buffer_process);
8287 defsubr (&Sprocess_inherit_coding_system_flag);
8288 defsubr (&Slist_system_processes);
8289 defsubr (&Ssystem_process_attributeses);
8290 }
8291
8292 \f
8293 #endif /* not subprocesses */
8294
8295 /* arch-tag: 3706c011-7b9a-4117-bd4f-59e7f701a4c4
8296 (do not change this comment) */